Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23from functools import reduce
  24
  25from sqlglot._typing import E
  26from sqlglot.errors import ParseError
  27from sqlglot.helper import (
  28    AutoName,
  29    camel_to_snake_case,
  30    ensure_collection,
  31    ensure_list,
  32    seq_get,
  33    subclasses,
  34)
  35from sqlglot.tokens import Token
  36
  37if t.TYPE_CHECKING:
  38    from sqlglot.dialects.dialect import DialectType
  39
  40
  41class _Expression(type):
  42    def __new__(cls, clsname, bases, attrs):
  43        klass = super().__new__(cls, clsname, bases, attrs)
  44
  45        # When an Expression class is created, its key is automatically set to be
  46        # the lowercase version of the class' name.
  47        klass.key = clsname.lower()
  48
  49        # This is so that docstrings are not inherited in pdoc
  50        klass.__doc__ = klass.__doc__ or ""
  51
  52        return klass
  53
  54
  55SQLGLOT_META = "sqlglot.meta"
  56
  57
  58class Expression(metaclass=_Expression):
  59    """
  60    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  61    context, such as its child expressions, their names (arg keys), and whether a given child expression
  62    is optional or not.
  63
  64    Attributes:
  65        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  66            and representing expressions as strings.
  67        arg_types: determines what arguments (child nodes) are supported by an expression. It
  68            maps arg keys to booleans that indicate whether the corresponding args are optional.
  69        parent: a reference to the parent expression (or None, in case of root expressions).
  70        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  71            uses to refer to it.
  72        comments: a list of comments that are associated with a given expression. This is used in
  73            order to preserve comments when transpiling SQL code.
  74        type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  75            optimizer, in order to enable some transformations that require type information.
  76        meta: a dictionary that can be used to store useful metadata for a given expression.
  77
  78    Example:
  79        >>> class Foo(Expression):
  80        ...     arg_types = {"this": True, "expression": False}
  81
  82        The above definition informs us that Foo is an Expression that requires an argument called
  83        "this" and may also optionally receive an argument called "expression".
  84
  85    Args:
  86        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  87    """
  88
  89    key = "expression"
  90    arg_types = {"this": True}
  91    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  92
  93    def __init__(self, **args: t.Any):
  94        self.args: t.Dict[str, t.Any] = args
  95        self.parent: t.Optional[Expression] = None
  96        self.arg_key: t.Optional[str] = None
  97        self.comments: t.Optional[t.List[str]] = None
  98        self._type: t.Optional[DataType] = None
  99        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 100        self._hash: t.Optional[int] = None
 101
 102        for arg_key, value in self.args.items():
 103            self._set_parent(arg_key, value)
 104
 105    def __eq__(self, other) -> bool:
 106        return type(self) is type(other) and hash(self) == hash(other)
 107
 108    @property
 109    def hashable_args(self) -> t.Any:
 110        return frozenset(
 111            (k, tuple(_norm_arg(a) for a in v) if type(v) is list else _norm_arg(v))
 112            for k, v in self.args.items()
 113            if not (v is None or v is False or (type(v) is list and not v))
 114        )
 115
 116    def __hash__(self) -> int:
 117        if self._hash is not None:
 118            return self._hash
 119
 120        return hash((self.__class__, self.hashable_args))
 121
 122    @property
 123    def this(self):
 124        """
 125        Retrieves the argument with key "this".
 126        """
 127        return self.args.get("this")
 128
 129    @property
 130    def expression(self):
 131        """
 132        Retrieves the argument with key "expression".
 133        """
 134        return self.args.get("expression")
 135
 136    @property
 137    def expressions(self):
 138        """
 139        Retrieves the argument with key "expressions".
 140        """
 141        return self.args.get("expressions") or []
 142
 143    def text(self, key) -> str:
 144        """
 145        Returns a textual representation of the argument corresponding to "key". This can only be used
 146        for args that are strings or leaf Expression instances, such as identifiers and literals.
 147        """
 148        field = self.args.get(key)
 149        if isinstance(field, str):
 150            return field
 151        if isinstance(field, (Identifier, Literal, Var)):
 152            return field.this
 153        if isinstance(field, (Star, Null)):
 154            return field.name
 155        return ""
 156
 157    @property
 158    def is_string(self) -> bool:
 159        """
 160        Checks whether a Literal expression is a string.
 161        """
 162        return isinstance(self, Literal) and self.args["is_string"]
 163
 164    @property
 165    def is_number(self) -> bool:
 166        """
 167        Checks whether a Literal expression is a number.
 168        """
 169        return isinstance(self, Literal) and not self.args["is_string"]
 170
 171    @property
 172    def is_int(self) -> bool:
 173        """
 174        Checks whether a Literal expression is an integer.
 175        """
 176        if self.is_number:
 177            try:
 178                int(self.name)
 179                return True
 180            except ValueError:
 181                pass
 182        return False
 183
 184    @property
 185    def is_star(self) -> bool:
 186        """Checks whether an expression is a star."""
 187        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 188
 189    @property
 190    def alias(self) -> str:
 191        """
 192        Returns the alias of the expression, or an empty string if it's not aliased.
 193        """
 194        if isinstance(self.args.get("alias"), TableAlias):
 195            return self.args["alias"].name
 196        return self.text("alias")
 197
 198    @property
 199    def alias_column_names(self) -> t.List[str]:
 200        table_alias = self.args.get("alias")
 201        if not table_alias:
 202            return []
 203        return [c.name for c in table_alias.args.get("columns") or []]
 204
 205    @property
 206    def name(self) -> str:
 207        return self.text("this")
 208
 209    @property
 210    def alias_or_name(self) -> str:
 211        return self.alias or self.name
 212
 213    @property
 214    def output_name(self) -> str:
 215        """
 216        Name of the output column if this expression is a selection.
 217
 218        If the Expression has no output name, an empty string is returned.
 219
 220        Example:
 221            >>> from sqlglot import parse_one
 222            >>> parse_one("SELECT a").expressions[0].output_name
 223            'a'
 224            >>> parse_one("SELECT b AS c").expressions[0].output_name
 225            'c'
 226            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 227            ''
 228        """
 229        return ""
 230
 231    @property
 232    def type(self) -> t.Optional[DataType]:
 233        return self._type
 234
 235    @type.setter
 236    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 237        if dtype and not isinstance(dtype, DataType):
 238            dtype = DataType.build(dtype)
 239        self._type = dtype  # type: ignore
 240
 241    @property
 242    def meta(self) -> t.Dict[str, t.Any]:
 243        if self._meta is None:
 244            self._meta = {}
 245        return self._meta
 246
 247    def __deepcopy__(self, memo):
 248        copy = self.__class__(**deepcopy(self.args))
 249        if self.comments is not None:
 250            copy.comments = deepcopy(self.comments)
 251
 252        if self._type is not None:
 253            copy._type = self._type.copy()
 254
 255        if self._meta is not None:
 256            copy._meta = deepcopy(self._meta)
 257
 258        return copy
 259
 260    def copy(self):
 261        """
 262        Returns a deep copy of the expression.
 263        """
 264        new = deepcopy(self)
 265        new.parent = self.parent
 266        return new
 267
 268    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
 269        if self.comments is None:
 270            self.comments = []
 271        if comments:
 272            for comment in comments:
 273                _, *meta = comment.split(SQLGLOT_META)
 274                if meta:
 275                    for kv in "".join(meta).split(","):
 276                        k, *v = kv.split("=")
 277                        value = v[0].strip() if v else True
 278                        self.meta[k.strip()] = value
 279                self.comments.append(comment)
 280
 281    def append(self, arg_key: str, value: t.Any) -> None:
 282        """
 283        Appends value to arg_key if it's a list or sets it as a new list.
 284
 285        Args:
 286            arg_key (str): name of the list expression arg
 287            value (Any): value to append to the list
 288        """
 289        if not isinstance(self.args.get(arg_key), list):
 290            self.args[arg_key] = []
 291        self.args[arg_key].append(value)
 292        self._set_parent(arg_key, value)
 293
 294    def set(self, arg_key: str, value: t.Any) -> None:
 295        """
 296        Sets arg_key to value.
 297
 298        Args:
 299            arg_key: name of the expression arg.
 300            value: value to set the arg to.
 301        """
 302        if value is None:
 303            self.args.pop(arg_key, None)
 304            return
 305
 306        self.args[arg_key] = value
 307        self._set_parent(arg_key, value)
 308
 309    def _set_parent(self, arg_key: str, value: t.Any) -> None:
 310        if hasattr(value, "parent"):
 311            value.parent = self
 312            value.arg_key = arg_key
 313        elif type(value) is list:
 314            for v in value:
 315                if hasattr(v, "parent"):
 316                    v.parent = self
 317                    v.arg_key = arg_key
 318
 319    @property
 320    def depth(self) -> int:
 321        """
 322        Returns the depth of this tree.
 323        """
 324        if self.parent:
 325            return self.parent.depth + 1
 326        return 0
 327
 328    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 329        """Yields the key and expression for all arguments, exploding list args."""
 330        for k, vs in self.args.items():
 331            if type(vs) is list:
 332                for v in vs:
 333                    if hasattr(v, "parent"):
 334                        yield k, v
 335            else:
 336                if hasattr(vs, "parent"):
 337                    yield k, vs
 338
 339    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
 340        """
 341        Returns the first node in this tree which matches at least one of
 342        the specified types.
 343
 344        Args:
 345            expression_types: the expression type(s) to match.
 346            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 347
 348        Returns:
 349            The node which matches the criteria or None if no such node was found.
 350        """
 351        return next(self.find_all(*expression_types, bfs=bfs), None)
 352
 353    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
 354        """
 355        Returns a generator object which visits all nodes in this tree and only
 356        yields those that match at least one of the specified expression types.
 357
 358        Args:
 359            expression_types: the expression type(s) to match.
 360            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 361
 362        Returns:
 363            The generator object.
 364        """
 365        for expression, *_ in self.walk(bfs=bfs):
 366            if isinstance(expression, expression_types):
 367                yield expression
 368
 369    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
 370        """
 371        Returns a nearest parent matching expression_types.
 372
 373        Args:
 374            expression_types: the expression type(s) to match.
 375
 376        Returns:
 377            The parent node.
 378        """
 379        ancestor = self.parent
 380        while ancestor and not isinstance(ancestor, expression_types):
 381            ancestor = ancestor.parent
 382        return t.cast(E, ancestor)
 383
 384    @property
 385    def parent_select(self) -> t.Optional[Select]:
 386        """
 387        Returns the parent select statement.
 388        """
 389        return self.find_ancestor(Select)
 390
 391    @property
 392    def same_parent(self) -> bool:
 393        """Returns if the parent is the same class as itself."""
 394        return type(self.parent) is self.__class__
 395
 396    def root(self) -> Expression:
 397        """
 398        Returns the root expression of this tree.
 399        """
 400        expression = self
 401        while expression.parent:
 402            expression = expression.parent
 403        return expression
 404
 405    def walk(self, bfs=True, prune=None):
 406        """
 407        Returns a generator object which visits all nodes in this tree.
 408
 409        Args:
 410            bfs (bool): if set to True the BFS traversal order will be applied,
 411                otherwise the DFS traversal will be used instead.
 412            prune ((node, parent, arg_key) -> bool): callable that returns True if
 413                the generator should stop traversing this branch of the tree.
 414
 415        Returns:
 416            the generator object.
 417        """
 418        if bfs:
 419            yield from self.bfs(prune=prune)
 420        else:
 421            yield from self.dfs(prune=prune)
 422
 423    def dfs(self, parent=None, key=None, prune=None):
 424        """
 425        Returns a generator object which visits all nodes in this tree in
 426        the DFS (Depth-first) order.
 427
 428        Returns:
 429            The generator object.
 430        """
 431        parent = parent or self.parent
 432        yield self, parent, key
 433        if prune and prune(self, parent, key):
 434            return
 435
 436        for k, v in self.iter_expressions():
 437            yield from v.dfs(self, k, prune)
 438
 439    def bfs(self, prune=None):
 440        """
 441        Returns a generator object which visits all nodes in this tree in
 442        the BFS (Breadth-first) order.
 443
 444        Returns:
 445            The generator object.
 446        """
 447        queue = deque([(self, self.parent, None)])
 448
 449        while queue:
 450            item, parent, key = queue.popleft()
 451
 452            yield item, parent, key
 453            if prune and prune(item, parent, key):
 454                continue
 455
 456            for k, v in item.iter_expressions():
 457                queue.append((v, item, k))
 458
 459    def unnest(self):
 460        """
 461        Returns the first non parenthesis child or self.
 462        """
 463        expression = self
 464        while type(expression) is Paren:
 465            expression = expression.this
 466        return expression
 467
 468    def unalias(self):
 469        """
 470        Returns the inner expression if this is an Alias.
 471        """
 472        if isinstance(self, Alias):
 473            return self.this
 474        return self
 475
 476    def unnest_operands(self):
 477        """
 478        Returns unnested operands as a tuple.
 479        """
 480        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 481
 482    def flatten(self, unnest=True):
 483        """
 484        Returns a generator which yields child nodes who's parents are the same class.
 485
 486        A AND B AND C -> [A, B, C]
 487        """
 488        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 489            if not type(node) is self.__class__:
 490                yield node.unnest() if unnest else node
 491
 492    def __str__(self) -> str:
 493        return self.sql()
 494
 495    def __repr__(self) -> str:
 496        return self._to_s()
 497
 498    def sql(self, dialect: DialectType = None, **opts) -> str:
 499        """
 500        Returns SQL string representation of this tree.
 501
 502        Args:
 503            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 504            opts: other `sqlglot.generator.Generator` options.
 505
 506        Returns:
 507            The SQL string.
 508        """
 509        from sqlglot.dialects import Dialect
 510
 511        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 512
 513    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 514        indent = "" if not level else "\n"
 515        indent += "".join(["  "] * level)
 516        left = f"({self.key.upper()} "
 517
 518        args: t.Dict[str, t.Any] = {
 519            k: ", ".join(
 520                v._to_s(hide_missing=hide_missing, level=level + 1)
 521                if hasattr(v, "_to_s")
 522                else str(v)
 523                for v in ensure_list(vs)
 524                if v is not None
 525            )
 526            for k, vs in self.args.items()
 527        }
 528        args["comments"] = self.comments
 529        args["type"] = self.type
 530        args = {k: v for k, v in args.items() if v or not hide_missing}
 531
 532        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 533        right += ")"
 534
 535        return indent + left + right
 536
 537    def transform(self, fun, *args, copy=True, **kwargs):
 538        """
 539        Recursively visits all tree nodes (excluding already transformed ones)
 540        and applies the given transformation function to each node.
 541
 542        Args:
 543            fun (function): a function which takes a node as an argument and returns a
 544                new transformed node or the same node without modifications. If the function
 545                returns None, then the corresponding node will be removed from the syntax tree.
 546            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 547                modified in place.
 548
 549        Returns:
 550            The transformed tree.
 551        """
 552        node = self.copy() if copy else self
 553        new_node = fun(node, *args, **kwargs)
 554
 555        if new_node is None or not isinstance(new_node, Expression):
 556            return new_node
 557        if new_node is not node:
 558            new_node.parent = node.parent
 559            return new_node
 560
 561        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 562        return new_node
 563
 564    @t.overload
 565    def replace(self, expression: E) -> E:
 566        ...
 567
 568    @t.overload
 569    def replace(self, expression: None) -> None:
 570        ...
 571
 572    def replace(self, expression):
 573        """
 574        Swap out this expression with a new expression.
 575
 576        For example::
 577
 578            >>> tree = Select().select("x").from_("tbl")
 579            >>> tree.find(Column).replace(Column(this="y"))
 580            (COLUMN this: y)
 581            >>> tree.sql()
 582            'SELECT y FROM tbl'
 583
 584        Args:
 585            expression: new node
 586
 587        Returns:
 588            The new expression or expressions.
 589        """
 590        if not self.parent:
 591            return expression
 592
 593        parent = self.parent
 594        self.parent = None
 595
 596        replace_children(parent, lambda child: expression if child is self else child)
 597        return expression
 598
 599    def pop(self: E) -> E:
 600        """
 601        Remove this expression from its AST.
 602
 603        Returns:
 604            The popped expression.
 605        """
 606        self.replace(None)
 607        return self
 608
 609    def assert_is(self, type_: t.Type[E]) -> E:
 610        """
 611        Assert that this `Expression` is an instance of `type_`.
 612
 613        If it is NOT an instance of `type_`, this raises an assertion error.
 614        Otherwise, this returns this expression.
 615
 616        Examples:
 617            This is useful for type security in chained expressions:
 618
 619            >>> import sqlglot
 620            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 621            'SELECT x, z FROM y'
 622        """
 623        assert isinstance(self, type_)
 624        return self
 625
 626    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 627        """
 628        Checks if this expression is valid (e.g. all mandatory args are set).
 629
 630        Args:
 631            args: a sequence of values that were used to instantiate a Func expression. This is used
 632                to check that the provided arguments don't exceed the function argument limit.
 633
 634        Returns:
 635            A list of error messages for all possible errors that were found.
 636        """
 637        errors: t.List[str] = []
 638
 639        for k in self.args:
 640            if k not in self.arg_types:
 641                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 642        for k, mandatory in self.arg_types.items():
 643            v = self.args.get(k)
 644            if mandatory and (v is None or (isinstance(v, list) and not v)):
 645                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 646
 647        if (
 648            args
 649            and isinstance(self, Func)
 650            and len(args) > len(self.arg_types)
 651            and not self.is_var_len_args
 652        ):
 653            errors.append(
 654                f"The number of provided arguments ({len(args)}) is greater than "
 655                f"the maximum number of supported arguments ({len(self.arg_types)})"
 656            )
 657
 658        return errors
 659
 660    def dump(self):
 661        """
 662        Dump this Expression to a JSON-serializable dict.
 663        """
 664        from sqlglot.serde import dump
 665
 666        return dump(self)
 667
 668    @classmethod
 669    def load(cls, obj):
 670        """
 671        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 672        """
 673        from sqlglot.serde import load
 674
 675        return load(obj)
 676
 677    def and_(
 678        self,
 679        *expressions: t.Optional[ExpOrStr],
 680        dialect: DialectType = None,
 681        copy: bool = True,
 682        **opts,
 683    ) -> Condition:
 684        """
 685        AND this condition with one or multiple expressions.
 686
 687        Example:
 688            >>> condition("x=1").and_("y=1").sql()
 689            'x = 1 AND y = 1'
 690
 691        Args:
 692            *expressions: the SQL code strings to parse.
 693                If an `Expression` instance is passed, it will be used as-is.
 694            dialect: the dialect used to parse the input expression.
 695            copy: whether or not to copy the involved expressions (only applies to Expressions).
 696            opts: other options to use to parse the input expressions.
 697
 698        Returns:
 699            The new And condition.
 700        """
 701        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
 702
 703    def or_(
 704        self,
 705        *expressions: t.Optional[ExpOrStr],
 706        dialect: DialectType = None,
 707        copy: bool = True,
 708        **opts,
 709    ) -> Condition:
 710        """
 711        OR this condition with one or multiple expressions.
 712
 713        Example:
 714            >>> condition("x=1").or_("y=1").sql()
 715            'x = 1 OR y = 1'
 716
 717        Args:
 718            *expressions: the SQL code strings to parse.
 719                If an `Expression` instance is passed, it will be used as-is.
 720            dialect: the dialect used to parse the input expression.
 721            copy: whether or not to copy the involved expressions (only applies to Expressions).
 722            opts: other options to use to parse the input expressions.
 723
 724        Returns:
 725            The new Or condition.
 726        """
 727        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
 728
 729    def not_(self, copy: bool = True):
 730        """
 731        Wrap this condition with NOT.
 732
 733        Example:
 734            >>> condition("x=1").not_().sql()
 735            'NOT x = 1'
 736
 737        Args:
 738            copy: whether or not to copy this object.
 739
 740        Returns:
 741            The new Not instance.
 742        """
 743        return not_(self, copy=copy)
 744
 745    def as_(
 746        self,
 747        alias: str | Identifier,
 748        quoted: t.Optional[bool] = None,
 749        dialect: DialectType = None,
 750        copy: bool = True,
 751        **opts,
 752    ) -> Alias:
 753        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
 754
 755    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
 756        this = self.copy()
 757        other = convert(other, copy=True)
 758        if not isinstance(this, klass) and not isinstance(other, klass):
 759            this = _wrap(this, Binary)
 760            other = _wrap(other, Binary)
 761        if reverse:
 762            return klass(this=other, expression=this)
 763        return klass(this=this, expression=other)
 764
 765    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]) -> Bracket:
 766        return Bracket(
 767            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
 768        )
 769
 770    def __iter__(self) -> t.Iterator:
 771        if "expressions" in self.arg_types:
 772            return iter(self.args.get("expressions") or [])
 773        # We define this because __getitem__ converts Expression into an iterable, which is
 774        # problematic because one can hit infinite loops if they do "for x in some_expr: ..."
 775        # See: https://peps.python.org/pep-0234/
 776        raise TypeError(f"'{self.__class__.__name__}' object is not iterable")
 777
 778    def isin(
 779        self,
 780        *expressions: t.Any,
 781        query: t.Optional[ExpOrStr] = None,
 782        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
 783        copy: bool = True,
 784        **opts,
 785    ) -> In:
 786        return In(
 787            this=maybe_copy(self, copy),
 788            expressions=[convert(e, copy=copy) for e in expressions],
 789            query=maybe_parse(query, copy=copy, **opts) if query else None,
 790            unnest=Unnest(
 791                expressions=[
 792                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
 793                ]
 794            )
 795            if unnest
 796            else None,
 797        )
 798
 799    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
 800        return Between(
 801            this=maybe_copy(self, copy),
 802            low=convert(low, copy=copy, **opts),
 803            high=convert(high, copy=copy, **opts),
 804        )
 805
 806    def is_(self, other: ExpOrStr) -> Is:
 807        return self._binop(Is, other)
 808
 809    def like(self, other: ExpOrStr) -> Like:
 810        return self._binop(Like, other)
 811
 812    def ilike(self, other: ExpOrStr) -> ILike:
 813        return self._binop(ILike, other)
 814
 815    def eq(self, other: t.Any) -> EQ:
 816        return self._binop(EQ, other)
 817
 818    def neq(self, other: t.Any) -> NEQ:
 819        return self._binop(NEQ, other)
 820
 821    def rlike(self, other: ExpOrStr) -> RegexpLike:
 822        return self._binop(RegexpLike, other)
 823
 824    def __lt__(self, other: t.Any) -> LT:
 825        return self._binop(LT, other)
 826
 827    def __le__(self, other: t.Any) -> LTE:
 828        return self._binop(LTE, other)
 829
 830    def __gt__(self, other: t.Any) -> GT:
 831        return self._binop(GT, other)
 832
 833    def __ge__(self, other: t.Any) -> GTE:
 834        return self._binop(GTE, other)
 835
 836    def __add__(self, other: t.Any) -> Add:
 837        return self._binop(Add, other)
 838
 839    def __radd__(self, other: t.Any) -> Add:
 840        return self._binop(Add, other, reverse=True)
 841
 842    def __sub__(self, other: t.Any) -> Sub:
 843        return self._binop(Sub, other)
 844
 845    def __rsub__(self, other: t.Any) -> Sub:
 846        return self._binop(Sub, other, reverse=True)
 847
 848    def __mul__(self, other: t.Any) -> Mul:
 849        return self._binop(Mul, other)
 850
 851    def __rmul__(self, other: t.Any) -> Mul:
 852        return self._binop(Mul, other, reverse=True)
 853
 854    def __truediv__(self, other: t.Any) -> Div:
 855        return self._binop(Div, other)
 856
 857    def __rtruediv__(self, other: t.Any) -> Div:
 858        return self._binop(Div, other, reverse=True)
 859
 860    def __floordiv__(self, other: t.Any) -> IntDiv:
 861        return self._binop(IntDiv, other)
 862
 863    def __rfloordiv__(self, other: t.Any) -> IntDiv:
 864        return self._binop(IntDiv, other, reverse=True)
 865
 866    def __mod__(self, other: t.Any) -> Mod:
 867        return self._binop(Mod, other)
 868
 869    def __rmod__(self, other: t.Any) -> Mod:
 870        return self._binop(Mod, other, reverse=True)
 871
 872    def __pow__(self, other: t.Any) -> Pow:
 873        return self._binop(Pow, other)
 874
 875    def __rpow__(self, other: t.Any) -> Pow:
 876        return self._binop(Pow, other, reverse=True)
 877
 878    def __and__(self, other: t.Any) -> And:
 879        return self._binop(And, other)
 880
 881    def __rand__(self, other: t.Any) -> And:
 882        return self._binop(And, other, reverse=True)
 883
 884    def __or__(self, other: t.Any) -> Or:
 885        return self._binop(Or, other)
 886
 887    def __ror__(self, other: t.Any) -> Or:
 888        return self._binop(Or, other, reverse=True)
 889
 890    def __neg__(self) -> Neg:
 891        return Neg(this=_wrap(self.copy(), Binary))
 892
 893    def __invert__(self) -> Not:
 894        return not_(self.copy())
 895
 896
 897IntoType = t.Union[
 898    str,
 899    t.Type[Expression],
 900    t.Collection[t.Union[str, t.Type[Expression]]],
 901]
 902ExpOrStr = t.Union[str, Expression]
 903
 904
 905class Condition(Expression):
 906    """Logical conditions like x AND y, or simply x"""
 907
 908
 909class Predicate(Condition):
 910    """Relationships like x = y, x > 1, x >= y."""
 911
 912
 913class DerivedTable(Expression):
 914    @property
 915    def selects(self) -> t.List[Expression]:
 916        return self.this.selects if isinstance(self.this, Subqueryable) else []
 917
 918    @property
 919    def named_selects(self) -> t.List[str]:
 920        return [select.output_name for select in self.selects]
 921
 922
 923class Unionable(Expression):
 924    def union(
 925        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 926    ) -> Unionable:
 927        """
 928        Builds a UNION expression.
 929
 930        Example:
 931            >>> import sqlglot
 932            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 933            'SELECT * FROM foo UNION SELECT * FROM bla'
 934
 935        Args:
 936            expression: the SQL code string.
 937                If an `Expression` instance is passed, it will be used as-is.
 938            distinct: set the DISTINCT flag if and only if this is true.
 939            dialect: the dialect used to parse the input expression.
 940            opts: other options to use to parse the input expressions.
 941
 942        Returns:
 943            The new Union expression.
 944        """
 945        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 946
 947    def intersect(
 948        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 949    ) -> Unionable:
 950        """
 951        Builds an INTERSECT expression.
 952
 953        Example:
 954            >>> import sqlglot
 955            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 956            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 957
 958        Args:
 959            expression: the SQL code string.
 960                If an `Expression` instance is passed, it will be used as-is.
 961            distinct: set the DISTINCT flag if and only if this is true.
 962            dialect: the dialect used to parse the input expression.
 963            opts: other options to use to parse the input expressions.
 964
 965        Returns:
 966            The new Intersect expression.
 967        """
 968        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 969
 970    def except_(
 971        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 972    ) -> Unionable:
 973        """
 974        Builds an EXCEPT expression.
 975
 976        Example:
 977            >>> import sqlglot
 978            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 979            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 980
 981        Args:
 982            expression: the SQL code string.
 983                If an `Expression` instance is passed, it will be used as-is.
 984            distinct: set the DISTINCT flag if and only if this is true.
 985            dialect: the dialect used to parse the input expression.
 986            opts: other options to use to parse the input expressions.
 987
 988        Returns:
 989            The new Except expression.
 990        """
 991        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 992
 993
 994class UDTF(DerivedTable, Unionable):
 995    @property
 996    def selects(self) -> t.List[Expression]:
 997        alias = self.args.get("alias")
 998        return alias.columns if alias else []
 999
1000
1001class Cache(Expression):
1002    arg_types = {
1003        "with": False,
1004        "this": True,
1005        "lazy": False,
1006        "options": False,
1007        "expression": False,
1008    }
1009
1010
1011class Uncache(Expression):
1012    arg_types = {"this": True, "exists": False}
1013
1014
1015class DDL(Expression):
1016    @property
1017    def ctes(self):
1018        with_ = self.args.get("with")
1019        if not with_:
1020            return []
1021        return with_.expressions
1022
1023    @property
1024    def named_selects(self) -> t.List[str]:
1025        if isinstance(self.expression, Subqueryable):
1026            return self.expression.named_selects
1027        return []
1028
1029    @property
1030    def selects(self) -> t.List[Expression]:
1031        if isinstance(self.expression, Subqueryable):
1032            return self.expression.selects
1033        return []
1034
1035
1036class Create(DDL):
1037    arg_types = {
1038        "with": False,
1039        "this": True,
1040        "kind": True,
1041        "expression": False,
1042        "exists": False,
1043        "properties": False,
1044        "replace": False,
1045        "unique": False,
1046        "indexes": False,
1047        "no_schema_binding": False,
1048        "begin": False,
1049        "end": False,
1050        "clone": False,
1051    }
1052
1053
1054# https://docs.snowflake.com/en/sql-reference/sql/create-clone
1055# https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_table_clone_statement
1056# https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_table_copy
1057class Clone(Expression):
1058    arg_types = {
1059        "this": True,
1060        "when": False,
1061        "kind": False,
1062        "shallow": False,
1063        "expression": False,
1064        "copy": False,
1065    }
1066
1067
1068class Describe(Expression):
1069    arg_types = {"this": True, "kind": False, "expressions": False}
1070
1071
1072class Kill(Expression):
1073    arg_types = {"this": True, "kind": False}
1074
1075
1076class Pragma(Expression):
1077    pass
1078
1079
1080class Set(Expression):
1081    arg_types = {"expressions": False, "unset": False, "tag": False}
1082
1083
1084class SetItem(Expression):
1085    arg_types = {
1086        "this": False,
1087        "expressions": False,
1088        "kind": False,
1089        "collate": False,  # MySQL SET NAMES statement
1090        "global": False,
1091    }
1092
1093
1094class Show(Expression):
1095    arg_types = {
1096        "this": True,
1097        "target": False,
1098        "offset": False,
1099        "limit": False,
1100        "like": False,
1101        "where": False,
1102        "db": False,
1103        "scope": False,
1104        "scope_kind": False,
1105        "full": False,
1106        "mutex": False,
1107        "query": False,
1108        "channel": False,
1109        "global": False,
1110        "log": False,
1111        "position": False,
1112        "types": False,
1113    }
1114
1115
1116class UserDefinedFunction(Expression):
1117    arg_types = {"this": True, "expressions": False, "wrapped": False}
1118
1119
1120class CharacterSet(Expression):
1121    arg_types = {"this": True, "default": False}
1122
1123
1124class With(Expression):
1125    arg_types = {"expressions": True, "recursive": False}
1126
1127    @property
1128    def recursive(self) -> bool:
1129        return bool(self.args.get("recursive"))
1130
1131
1132class WithinGroup(Expression):
1133    arg_types = {"this": True, "expression": False}
1134
1135
1136class CTE(DerivedTable):
1137    arg_types = {"this": True, "alias": True}
1138
1139
1140class TableAlias(Expression):
1141    arg_types = {"this": False, "columns": False}
1142
1143    @property
1144    def columns(self):
1145        return self.args.get("columns") or []
1146
1147
1148class BitString(Condition):
1149    pass
1150
1151
1152class HexString(Condition):
1153    pass
1154
1155
1156class ByteString(Condition):
1157    pass
1158
1159
1160class RawString(Condition):
1161    pass
1162
1163
1164class Column(Condition):
1165    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1166
1167    @property
1168    def table(self) -> str:
1169        return self.text("table")
1170
1171    @property
1172    def db(self) -> str:
1173        return self.text("db")
1174
1175    @property
1176    def catalog(self) -> str:
1177        return self.text("catalog")
1178
1179    @property
1180    def output_name(self) -> str:
1181        return self.name
1182
1183    @property
1184    def parts(self) -> t.List[Identifier]:
1185        """Return the parts of a column in order catalog, db, table, name."""
1186        return [
1187            t.cast(Identifier, self.args[part])
1188            for part in ("catalog", "db", "table", "this")
1189            if self.args.get(part)
1190        ]
1191
1192    def to_dot(self) -> Dot | Identifier:
1193        """Converts the column into a dot expression."""
1194        parts = self.parts
1195        parent = self.parent
1196
1197        while parent:
1198            if isinstance(parent, Dot):
1199                parts.append(parent.expression)
1200            parent = parent.parent
1201
1202        return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]
1203
1204
1205class ColumnPosition(Expression):
1206    arg_types = {"this": False, "position": True}
1207
1208
1209class ColumnDef(Expression):
1210    arg_types = {
1211        "this": True,
1212        "kind": False,
1213        "constraints": False,
1214        "exists": False,
1215        "position": False,
1216    }
1217
1218    @property
1219    def constraints(self) -> t.List[ColumnConstraint]:
1220        return self.args.get("constraints") or []
1221
1222
1223class AlterColumn(Expression):
1224    arg_types = {
1225        "this": True,
1226        "dtype": False,
1227        "collate": False,
1228        "using": False,
1229        "default": False,
1230        "drop": False,
1231    }
1232
1233
1234class RenameTable(Expression):
1235    pass
1236
1237
1238class Comment(Expression):
1239    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
1240
1241
1242class Comprehension(Expression):
1243    arg_types = {"this": True, "expression": True, "iterator": True, "condition": False}
1244
1245
1246# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1247class MergeTreeTTLAction(Expression):
1248    arg_types = {
1249        "this": True,
1250        "delete": False,
1251        "recompress": False,
1252        "to_disk": False,
1253        "to_volume": False,
1254    }
1255
1256
1257# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1258class MergeTreeTTL(Expression):
1259    arg_types = {
1260        "expressions": True,
1261        "where": False,
1262        "group": False,
1263        "aggregates": False,
1264    }
1265
1266
1267# https://dev.mysql.com/doc/refman/8.0/en/create-table.html
1268class IndexConstraintOption(Expression):
1269    arg_types = {
1270        "key_block_size": False,
1271        "using": False,
1272        "parser": False,
1273        "comment": False,
1274        "visible": False,
1275        "engine_attr": False,
1276        "secondary_engine_attr": False,
1277    }
1278
1279
1280class ColumnConstraint(Expression):
1281    arg_types = {"this": False, "kind": True}
1282
1283    @property
1284    def kind(self) -> ColumnConstraintKind:
1285        return self.args["kind"]
1286
1287
1288class ColumnConstraintKind(Expression):
1289    pass
1290
1291
1292class AutoIncrementColumnConstraint(ColumnConstraintKind):
1293    pass
1294
1295
1296class CaseSpecificColumnConstraint(ColumnConstraintKind):
1297    arg_types = {"not_": True}
1298
1299
1300class CharacterSetColumnConstraint(ColumnConstraintKind):
1301    arg_types = {"this": True}
1302
1303
1304class CheckColumnConstraint(ColumnConstraintKind):
1305    pass
1306
1307
1308class ClusteredColumnConstraint(ColumnConstraintKind):
1309    pass
1310
1311
1312class CollateColumnConstraint(ColumnConstraintKind):
1313    pass
1314
1315
1316class CommentColumnConstraint(ColumnConstraintKind):
1317    pass
1318
1319
1320class CompressColumnConstraint(ColumnConstraintKind):
1321    pass
1322
1323
1324class DateFormatColumnConstraint(ColumnConstraintKind):
1325    arg_types = {"this": True}
1326
1327
1328class DefaultColumnConstraint(ColumnConstraintKind):
1329    pass
1330
1331
1332class EncodeColumnConstraint(ColumnConstraintKind):
1333    pass
1334
1335
1336class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1337    # this: True -> ALWAYS, this: False -> BY DEFAULT
1338    arg_types = {
1339        "this": False,
1340        "expression": False,
1341        "on_null": False,
1342        "start": False,
1343        "increment": False,
1344        "minvalue": False,
1345        "maxvalue": False,
1346        "cycle": False,
1347    }
1348
1349
1350# https://dev.mysql.com/doc/refman/8.0/en/create-table.html
1351class IndexColumnConstraint(ColumnConstraintKind):
1352    arg_types = {
1353        "this": False,
1354        "schema": True,
1355        "kind": False,
1356        "index_type": False,
1357        "options": False,
1358    }
1359
1360
1361class InlineLengthColumnConstraint(ColumnConstraintKind):
1362    pass
1363
1364
1365class NonClusteredColumnConstraint(ColumnConstraintKind):
1366    pass
1367
1368
1369class NotForReplicationColumnConstraint(ColumnConstraintKind):
1370    arg_types = {}
1371
1372
1373class NotNullColumnConstraint(ColumnConstraintKind):
1374    arg_types = {"allow_null": False}
1375
1376
1377# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1378class OnUpdateColumnConstraint(ColumnConstraintKind):
1379    pass
1380
1381
1382class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1383    arg_types = {"desc": False}
1384
1385
1386class TitleColumnConstraint(ColumnConstraintKind):
1387    pass
1388
1389
1390class UniqueColumnConstraint(ColumnConstraintKind):
1391    arg_types = {"this": False, "index_type": False}
1392
1393
1394class UppercaseColumnConstraint(ColumnConstraintKind):
1395    arg_types: t.Dict[str, t.Any] = {}
1396
1397
1398class PathColumnConstraint(ColumnConstraintKind):
1399    pass
1400
1401
1402# computed column expression
1403# https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver16
1404class ComputedColumnConstraint(ColumnConstraintKind):
1405    arg_types = {"this": True, "persisted": False, "not_null": False}
1406
1407
1408class Constraint(Expression):
1409    arg_types = {"this": True, "expressions": True}
1410
1411
1412class Delete(Expression):
1413    arg_types = {
1414        "with": False,
1415        "this": False,
1416        "using": False,
1417        "where": False,
1418        "returning": False,
1419        "limit": False,
1420        "tables": False,  # Multiple-Table Syntax (MySQL)
1421    }
1422
1423    def delete(
1424        self,
1425        table: ExpOrStr,
1426        dialect: DialectType = None,
1427        copy: bool = True,
1428        **opts,
1429    ) -> Delete:
1430        """
1431        Create a DELETE expression or replace the table on an existing DELETE expression.
1432
1433        Example:
1434            >>> delete("tbl").sql()
1435            'DELETE FROM tbl'
1436
1437        Args:
1438            table: the table from which to delete.
1439            dialect: the dialect used to parse the input expression.
1440            copy: if `False`, modify this expression instance in-place.
1441            opts: other options to use to parse the input expressions.
1442
1443        Returns:
1444            Delete: the modified expression.
1445        """
1446        return _apply_builder(
1447            expression=table,
1448            instance=self,
1449            arg="this",
1450            dialect=dialect,
1451            into=Table,
1452            copy=copy,
1453            **opts,
1454        )
1455
1456    def where(
1457        self,
1458        *expressions: t.Optional[ExpOrStr],
1459        append: bool = True,
1460        dialect: DialectType = None,
1461        copy: bool = True,
1462        **opts,
1463    ) -> Delete:
1464        """
1465        Append to or set the WHERE expressions.
1466
1467        Example:
1468            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1469            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1470
1471        Args:
1472            *expressions: the SQL code strings to parse.
1473                If an `Expression` instance is passed, it will be used as-is.
1474                Multiple expressions are combined with an AND operator.
1475            append: if `True`, AND the new expressions to any existing expression.
1476                Otherwise, this resets the expression.
1477            dialect: the dialect used to parse the input expressions.
1478            copy: if `False`, modify this expression instance in-place.
1479            opts: other options to use to parse the input expressions.
1480
1481        Returns:
1482            Delete: the modified expression.
1483        """
1484        return _apply_conjunction_builder(
1485            *expressions,
1486            instance=self,
1487            arg="where",
1488            append=append,
1489            into=Where,
1490            dialect=dialect,
1491            copy=copy,
1492            **opts,
1493        )
1494
1495    def returning(
1496        self,
1497        expression: ExpOrStr,
1498        dialect: DialectType = None,
1499        copy: bool = True,
1500        **opts,
1501    ) -> Delete:
1502        """
1503        Set the RETURNING expression. Not supported by all dialects.
1504
1505        Example:
1506            >>> delete("tbl").returning("*", dialect="postgres").sql()
1507            'DELETE FROM tbl RETURNING *'
1508
1509        Args:
1510            expression: the SQL code strings to parse.
1511                If an `Expression` instance is passed, it will be used as-is.
1512            dialect: the dialect used to parse the input expressions.
1513            copy: if `False`, modify this expression instance in-place.
1514            opts: other options to use to parse the input expressions.
1515
1516        Returns:
1517            Delete: the modified expression.
1518        """
1519        return _apply_builder(
1520            expression=expression,
1521            instance=self,
1522            arg="returning",
1523            prefix="RETURNING",
1524            dialect=dialect,
1525            copy=copy,
1526            into=Returning,
1527            **opts,
1528        )
1529
1530
1531class Drop(Expression):
1532    arg_types = {
1533        "this": False,
1534        "kind": False,
1535        "exists": False,
1536        "temporary": False,
1537        "materialized": False,
1538        "cascade": False,
1539        "constraints": False,
1540        "purge": False,
1541    }
1542
1543
1544class Filter(Expression):
1545    arg_types = {"this": True, "expression": True}
1546
1547
1548class Check(Expression):
1549    pass
1550
1551
1552# https://docs.snowflake.com/en/sql-reference/constructs/connect-by
1553class Connect(Expression):
1554    arg_types = {"start": False, "connect": True}
1555
1556
1557class Prior(Expression):
1558    pass
1559
1560
1561class Directory(Expression):
1562    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1563    arg_types = {"this": True, "local": False, "row_format": False}
1564
1565
1566class ForeignKey(Expression):
1567    arg_types = {
1568        "expressions": True,
1569        "reference": False,
1570        "delete": False,
1571        "update": False,
1572    }
1573
1574
1575class ColumnPrefix(Expression):
1576    arg_types = {"this": True, "expression": True}
1577
1578
1579class PrimaryKey(Expression):
1580    arg_types = {"expressions": True, "options": False}
1581
1582
1583# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1584# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1585class Into(Expression):
1586    arg_types = {"this": True, "temporary": False, "unlogged": False}
1587
1588
1589class From(Expression):
1590    @property
1591    def name(self) -> str:
1592        return self.this.name
1593
1594    @property
1595    def alias_or_name(self) -> str:
1596        return self.this.alias_or_name
1597
1598
1599class Having(Expression):
1600    pass
1601
1602
1603class Hint(Expression):
1604    arg_types = {"expressions": True}
1605
1606
1607class JoinHint(Expression):
1608    arg_types = {"this": True, "expressions": True}
1609
1610
1611class Identifier(Expression):
1612    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1613
1614    @property
1615    def quoted(self) -> bool:
1616        return bool(self.args.get("quoted"))
1617
1618    @property
1619    def hashable_args(self) -> t.Any:
1620        return (self.this, self.quoted)
1621
1622    @property
1623    def output_name(self) -> str:
1624        return self.name
1625
1626
1627# https://www.postgresql.org/docs/current/indexes-opclass.html
1628class Opclass(Expression):
1629    arg_types = {"this": True, "expression": True}
1630
1631
1632class Index(Expression):
1633    arg_types = {
1634        "this": False,
1635        "table": False,
1636        "using": False,
1637        "where": False,
1638        "columns": False,
1639        "unique": False,
1640        "primary": False,
1641        "amp": False,  # teradata
1642        "partition_by": False,  # teradata
1643        "where": False,  # postgres partial indexes
1644    }
1645
1646
1647class Insert(DDL):
1648    arg_types = {
1649        "with": False,
1650        "this": True,
1651        "expression": False,
1652        "conflict": False,
1653        "returning": False,
1654        "overwrite": False,
1655        "exists": False,
1656        "partition": False,
1657        "alternative": False,
1658        "where": False,
1659        "ignore": False,
1660        "by_name": False,
1661    }
1662
1663    def with_(
1664        self,
1665        alias: ExpOrStr,
1666        as_: ExpOrStr,
1667        recursive: t.Optional[bool] = None,
1668        append: bool = True,
1669        dialect: DialectType = None,
1670        copy: bool = True,
1671        **opts,
1672    ) -> Insert:
1673        """
1674        Append to or set the common table expressions.
1675
1676        Example:
1677            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1678            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1679
1680        Args:
1681            alias: the SQL code string to parse as the table name.
1682                If an `Expression` instance is passed, this is used as-is.
1683            as_: the SQL code string to parse as the table expression.
1684                If an `Expression` instance is passed, it will be used as-is.
1685            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1686            append: if `True`, add to any existing expressions.
1687                Otherwise, this resets the expressions.
1688            dialect: the dialect used to parse the input expression.
1689            copy: if `False`, modify this expression instance in-place.
1690            opts: other options to use to parse the input expressions.
1691
1692        Returns:
1693            The modified expression.
1694        """
1695        return _apply_cte_builder(
1696            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1697        )
1698
1699
1700class OnConflict(Expression):
1701    arg_types = {
1702        "duplicate": False,
1703        "expressions": False,
1704        "nothing": False,
1705        "key": False,
1706        "constraint": False,
1707    }
1708
1709
1710class Returning(Expression):
1711    arg_types = {"expressions": True, "into": False}
1712
1713
1714# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1715class Introducer(Expression):
1716    arg_types = {"this": True, "expression": True}
1717
1718
1719# national char, like n'utf8'
1720class National(Expression):
1721    pass
1722
1723
1724class LoadData(Expression):
1725    arg_types = {
1726        "this": True,
1727        "local": False,
1728        "overwrite": False,
1729        "inpath": True,
1730        "partition": False,
1731        "input_format": False,
1732        "serde": False,
1733    }
1734
1735
1736class Partition(Expression):
1737    arg_types = {"expressions": True}
1738
1739
1740class Fetch(Expression):
1741    arg_types = {
1742        "direction": False,
1743        "count": False,
1744        "percent": False,
1745        "with_ties": False,
1746    }
1747
1748
1749class Group(Expression):
1750    arg_types = {
1751        "expressions": False,
1752        "grouping_sets": False,
1753        "cube": False,
1754        "rollup": False,
1755        "totals": False,
1756        "all": False,
1757    }
1758
1759
1760class Lambda(Expression):
1761    arg_types = {"this": True, "expressions": True}
1762
1763
1764class Limit(Expression):
1765    arg_types = {"this": False, "expression": True, "offset": False}
1766
1767
1768class Literal(Condition):
1769    arg_types = {"this": True, "is_string": True}
1770
1771    @property
1772    def hashable_args(self) -> t.Any:
1773        return (self.this, self.args.get("is_string"))
1774
1775    @classmethod
1776    def number(cls, number) -> Literal:
1777        return cls(this=str(number), is_string=False)
1778
1779    @classmethod
1780    def string(cls, string) -> Literal:
1781        return cls(this=str(string), is_string=True)
1782
1783    @property
1784    def output_name(self) -> str:
1785        return self.name
1786
1787
1788class Join(Expression):
1789    arg_types = {
1790        "this": True,
1791        "on": False,
1792        "side": False,
1793        "kind": False,
1794        "using": False,
1795        "method": False,
1796        "global": False,
1797        "hint": False,
1798    }
1799
1800    @property
1801    def method(self) -> str:
1802        return self.text("method").upper()
1803
1804    @property
1805    def kind(self) -> str:
1806        return self.text("kind").upper()
1807
1808    @property
1809    def side(self) -> str:
1810        return self.text("side").upper()
1811
1812    @property
1813    def hint(self) -> str:
1814        return self.text("hint").upper()
1815
1816    @property
1817    def alias_or_name(self) -> str:
1818        return self.this.alias_or_name
1819
1820    def on(
1821        self,
1822        *expressions: t.Optional[ExpOrStr],
1823        append: bool = True,
1824        dialect: DialectType = None,
1825        copy: bool = True,
1826        **opts,
1827    ) -> Join:
1828        """
1829        Append to or set the ON expressions.
1830
1831        Example:
1832            >>> import sqlglot
1833            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1834            'JOIN x ON y = 1'
1835
1836        Args:
1837            *expressions: the SQL code strings to parse.
1838                If an `Expression` instance is passed, it will be used as-is.
1839                Multiple expressions are combined with an AND operator.
1840            append: if `True`, AND the new expressions to any existing expression.
1841                Otherwise, this resets the expression.
1842            dialect: the dialect used to parse the input expressions.
1843            copy: if `False`, modify this expression instance in-place.
1844            opts: other options to use to parse the input expressions.
1845
1846        Returns:
1847            The modified Join expression.
1848        """
1849        join = _apply_conjunction_builder(
1850            *expressions,
1851            instance=self,
1852            arg="on",
1853            append=append,
1854            dialect=dialect,
1855            copy=copy,
1856            **opts,
1857        )
1858
1859        if join.kind == "CROSS":
1860            join.set("kind", None)
1861
1862        return join
1863
1864    def using(
1865        self,
1866        *expressions: t.Optional[ExpOrStr],
1867        append: bool = True,
1868        dialect: DialectType = None,
1869        copy: bool = True,
1870        **opts,
1871    ) -> Join:
1872        """
1873        Append to or set the USING expressions.
1874
1875        Example:
1876            >>> import sqlglot
1877            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1878            'JOIN x USING (foo, bla)'
1879
1880        Args:
1881            *expressions: the SQL code strings to parse.
1882                If an `Expression` instance is passed, it will be used as-is.
1883            append: if `True`, concatenate the new expressions to the existing "using" list.
1884                Otherwise, this resets the expression.
1885            dialect: the dialect used to parse the input expressions.
1886            copy: if `False`, modify this expression instance in-place.
1887            opts: other options to use to parse the input expressions.
1888
1889        Returns:
1890            The modified Join expression.
1891        """
1892        join = _apply_list_builder(
1893            *expressions,
1894            instance=self,
1895            arg="using",
1896            append=append,
1897            dialect=dialect,
1898            copy=copy,
1899            **opts,
1900        )
1901
1902        if join.kind == "CROSS":
1903            join.set("kind", None)
1904
1905        return join
1906
1907
1908class Lateral(UDTF):
1909    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1910
1911
1912class MatchRecognize(Expression):
1913    arg_types = {
1914        "partition_by": False,
1915        "order": False,
1916        "measures": False,
1917        "rows": False,
1918        "after": False,
1919        "pattern": False,
1920        "define": False,
1921        "alias": False,
1922    }
1923
1924
1925# Clickhouse FROM FINAL modifier
1926# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1927class Final(Expression):
1928    pass
1929
1930
1931class Offset(Expression):
1932    arg_types = {"this": False, "expression": True}
1933
1934
1935class Order(Expression):
1936    arg_types = {"this": False, "expressions": True}
1937
1938
1939# hive specific sorts
1940# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1941class Cluster(Order):
1942    pass
1943
1944
1945class Distribute(Order):
1946    pass
1947
1948
1949class Sort(Order):
1950    pass
1951
1952
1953class Ordered(Expression):
1954    arg_types = {"this": True, "desc": False, "nulls_first": True}
1955
1956
1957class Property(Expression):
1958    arg_types = {"this": True, "value": True}
1959
1960
1961class AlgorithmProperty(Property):
1962    arg_types = {"this": True}
1963
1964
1965class AutoIncrementProperty(Property):
1966    arg_types = {"this": True}
1967
1968
1969class BlockCompressionProperty(Property):
1970    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1971
1972
1973class CharacterSetProperty(Property):
1974    arg_types = {"this": True, "default": True}
1975
1976
1977class ChecksumProperty(Property):
1978    arg_types = {"on": False, "default": False}
1979
1980
1981class CollateProperty(Property):
1982    arg_types = {"this": True}
1983
1984
1985class CopyGrantsProperty(Property):
1986    arg_types = {}
1987
1988
1989class DataBlocksizeProperty(Property):
1990    arg_types = {
1991        "size": False,
1992        "units": False,
1993        "minimum": False,
1994        "maximum": False,
1995        "default": False,
1996    }
1997
1998
1999class DefinerProperty(Property):
2000    arg_types = {"this": True}
2001
2002
2003class DistKeyProperty(Property):
2004    arg_types = {"this": True}
2005
2006
2007class DistStyleProperty(Property):
2008    arg_types = {"this": True}
2009
2010
2011class EngineProperty(Property):
2012    arg_types = {"this": True}
2013
2014
2015class HeapProperty(Property):
2016    arg_types = {}
2017
2018
2019class ToTableProperty(Property):
2020    arg_types = {"this": True}
2021
2022
2023class ExecuteAsProperty(Property):
2024    arg_types = {"this": True}
2025
2026
2027class ExternalProperty(Property):
2028    arg_types = {"this": False}
2029
2030
2031class FallbackProperty(Property):
2032    arg_types = {"no": True, "protection": False}
2033
2034
2035class FileFormatProperty(Property):
2036    arg_types = {"this": True}
2037
2038
2039class FreespaceProperty(Property):
2040    arg_types = {"this": True, "percent": False}
2041
2042
2043class InputOutputFormat(Expression):
2044    arg_types = {"input_format": False, "output_format": False}
2045
2046
2047class IsolatedLoadingProperty(Property):
2048    arg_types = {
2049        "no": True,
2050        "concurrent": True,
2051        "for_all": True,
2052        "for_insert": True,
2053        "for_none": True,
2054    }
2055
2056
2057class JournalProperty(Property):
2058    arg_types = {
2059        "no": False,
2060        "dual": False,
2061        "before": False,
2062        "local": False,
2063        "after": False,
2064    }
2065
2066
2067class LanguageProperty(Property):
2068    arg_types = {"this": True}
2069
2070
2071# spark ddl
2072class ClusteredByProperty(Property):
2073    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
2074
2075
2076class DictProperty(Property):
2077    arg_types = {"this": True, "kind": True, "settings": False}
2078
2079
2080class DictSubProperty(Property):
2081    pass
2082
2083
2084class DictRange(Property):
2085    arg_types = {"this": True, "min": True, "max": True}
2086
2087
2088# Clickhouse CREATE ... ON CLUSTER modifier
2089# https://clickhouse.com/docs/en/sql-reference/distributed-ddl
2090class OnCluster(Property):
2091    arg_types = {"this": True}
2092
2093
2094class LikeProperty(Property):
2095    arg_types = {"this": True, "expressions": False}
2096
2097
2098class LocationProperty(Property):
2099    arg_types = {"this": True}
2100
2101
2102class LockingProperty(Property):
2103    arg_types = {
2104        "this": False,
2105        "kind": True,
2106        "for_or_in": True,
2107        "lock_type": True,
2108        "override": False,
2109    }
2110
2111
2112class LogProperty(Property):
2113    arg_types = {"no": True}
2114
2115
2116class MaterializedProperty(Property):
2117    arg_types = {"this": False}
2118
2119
2120class MergeBlockRatioProperty(Property):
2121    arg_types = {"this": False, "no": False, "default": False, "percent": False}
2122
2123
2124class NoPrimaryIndexProperty(Property):
2125    arg_types = {}
2126
2127
2128class OnProperty(Property):
2129    arg_types = {"this": True}
2130
2131
2132class OnCommitProperty(Property):
2133    arg_types = {"delete": False}
2134
2135
2136class PartitionedByProperty(Property):
2137    arg_types = {"this": True}
2138
2139
2140class ReturnsProperty(Property):
2141    arg_types = {"this": True, "is_table": False, "table": False}
2142
2143
2144class RowFormatProperty(Property):
2145    arg_types = {"this": True}
2146
2147
2148class RowFormatDelimitedProperty(Property):
2149    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2150    arg_types = {
2151        "fields": False,
2152        "escaped": False,
2153        "collection_items": False,
2154        "map_keys": False,
2155        "lines": False,
2156        "null": False,
2157        "serde": False,
2158    }
2159
2160
2161class RowFormatSerdeProperty(Property):
2162    arg_types = {"this": True, "serde_properties": False}
2163
2164
2165# https://spark.apache.org/docs/3.1.2/sql-ref-syntax-qry-select-transform.html
2166class QueryTransform(Expression):
2167    arg_types = {
2168        "expressions": True,
2169        "command_script": True,
2170        "schema": False,
2171        "row_format_before": False,
2172        "record_writer": False,
2173        "row_format_after": False,
2174        "record_reader": False,
2175    }
2176
2177
2178class SampleProperty(Property):
2179    arg_types = {"this": True}
2180
2181
2182class SchemaCommentProperty(Property):
2183    arg_types = {"this": True}
2184
2185
2186class SerdeProperties(Property):
2187    arg_types = {"expressions": True}
2188
2189
2190class SetProperty(Property):
2191    arg_types = {"multi": True}
2192
2193
2194class SettingsProperty(Property):
2195    arg_types = {"expressions": True}
2196
2197
2198class SortKeyProperty(Property):
2199    arg_types = {"this": True, "compound": False}
2200
2201
2202class SqlSecurityProperty(Property):
2203    arg_types = {"definer": True}
2204
2205
2206class StabilityProperty(Property):
2207    arg_types = {"this": True}
2208
2209
2210class TemporaryProperty(Property):
2211    arg_types = {}
2212
2213
2214class TransientProperty(Property):
2215    arg_types = {"this": False}
2216
2217
2218class VolatileProperty(Property):
2219    arg_types = {"this": False}
2220
2221
2222class WithDataProperty(Property):
2223    arg_types = {"no": True, "statistics": False}
2224
2225
2226class WithJournalTableProperty(Property):
2227    arg_types = {"this": True}
2228
2229
2230class Properties(Expression):
2231    arg_types = {"expressions": True}
2232
2233    NAME_TO_PROPERTY = {
2234        "ALGORITHM": AlgorithmProperty,
2235        "AUTO_INCREMENT": AutoIncrementProperty,
2236        "CHARACTER SET": CharacterSetProperty,
2237        "CLUSTERED_BY": ClusteredByProperty,
2238        "COLLATE": CollateProperty,
2239        "COMMENT": SchemaCommentProperty,
2240        "DEFINER": DefinerProperty,
2241        "DISTKEY": DistKeyProperty,
2242        "DISTSTYLE": DistStyleProperty,
2243        "ENGINE": EngineProperty,
2244        "EXECUTE AS": ExecuteAsProperty,
2245        "FORMAT": FileFormatProperty,
2246        "LANGUAGE": LanguageProperty,
2247        "LOCATION": LocationProperty,
2248        "PARTITIONED_BY": PartitionedByProperty,
2249        "RETURNS": ReturnsProperty,
2250        "ROW_FORMAT": RowFormatProperty,
2251        "SORTKEY": SortKeyProperty,
2252    }
2253
2254    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2255
2256    # CREATE property locations
2257    # Form: schema specified
2258    #   create [POST_CREATE]
2259    #     table a [POST_NAME]
2260    #     (b int) [POST_SCHEMA]
2261    #     with ([POST_WITH])
2262    #     index (b) [POST_INDEX]
2263    #
2264    # Form: alias selection
2265    #   create [POST_CREATE]
2266    #     table a [POST_NAME]
2267    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2268    #     index (c) [POST_INDEX]
2269    class Location(AutoName):
2270        POST_CREATE = auto()
2271        POST_NAME = auto()
2272        POST_SCHEMA = auto()
2273        POST_WITH = auto()
2274        POST_ALIAS = auto()
2275        POST_EXPRESSION = auto()
2276        POST_INDEX = auto()
2277        UNSUPPORTED = auto()
2278
2279    @classmethod
2280    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2281        expressions = []
2282        for key, value in properties_dict.items():
2283            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2284            if property_cls:
2285                expressions.append(property_cls(this=convert(value)))
2286            else:
2287                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2288
2289        return cls(expressions=expressions)
2290
2291
2292class Qualify(Expression):
2293    pass
2294
2295
2296# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
2297class Return(Expression):
2298    pass
2299
2300
2301class Reference(Expression):
2302    arg_types = {"this": True, "expressions": False, "options": False}
2303
2304
2305class Tuple(Expression):
2306    arg_types = {"expressions": False}
2307
2308    def isin(
2309        self,
2310        *expressions: t.Any,
2311        query: t.Optional[ExpOrStr] = None,
2312        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2313        copy: bool = True,
2314        **opts,
2315    ) -> In:
2316        return In(
2317            this=maybe_copy(self, copy),
2318            expressions=[convert(e, copy=copy) for e in expressions],
2319            query=maybe_parse(query, copy=copy, **opts) if query else None,
2320            unnest=Unnest(
2321                expressions=[
2322                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2323                ]
2324            )
2325            if unnest
2326            else None,
2327        )
2328
2329
2330class Subqueryable(Unionable):
2331    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2332        """
2333        Convert this expression to an aliased expression that can be used as a Subquery.
2334
2335        Example:
2336            >>> subquery = Select().select("x").from_("tbl").subquery()
2337            >>> Select().select("x").from_(subquery).sql()
2338            'SELECT x FROM (SELECT x FROM tbl)'
2339
2340        Args:
2341            alias (str | Identifier): an optional alias for the subquery
2342            copy (bool): if `False`, modify this expression instance in-place.
2343
2344        Returns:
2345            Alias: the subquery
2346        """
2347        instance = maybe_copy(self, copy)
2348        if not isinstance(alias, Expression):
2349            alias = TableAlias(this=to_identifier(alias)) if alias else None
2350
2351        return Subquery(this=instance, alias=alias)
2352
2353    def limit(
2354        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2355    ) -> Select:
2356        raise NotImplementedError
2357
2358    @property
2359    def ctes(self):
2360        with_ = self.args.get("with")
2361        if not with_:
2362            return []
2363        return with_.expressions
2364
2365    @property
2366    def selects(self) -> t.List[Expression]:
2367        raise NotImplementedError("Subqueryable objects must implement `selects`")
2368
2369    @property
2370    def named_selects(self) -> t.List[str]:
2371        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2372
2373    def select(
2374        self,
2375        *expressions: t.Optional[ExpOrStr],
2376        append: bool = True,
2377        dialect: DialectType = None,
2378        copy: bool = True,
2379        **opts,
2380    ) -> Subqueryable:
2381        raise NotImplementedError("Subqueryable objects must implement `select`")
2382
2383    def with_(
2384        self,
2385        alias: ExpOrStr,
2386        as_: ExpOrStr,
2387        recursive: t.Optional[bool] = None,
2388        append: bool = True,
2389        dialect: DialectType = None,
2390        copy: bool = True,
2391        **opts,
2392    ) -> Subqueryable:
2393        """
2394        Append to or set the common table expressions.
2395
2396        Example:
2397            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2398            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2399
2400        Args:
2401            alias: the SQL code string to parse as the table name.
2402                If an `Expression` instance is passed, this is used as-is.
2403            as_: the SQL code string to parse as the table expression.
2404                If an `Expression` instance is passed, it will be used as-is.
2405            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2406            append: if `True`, add to any existing expressions.
2407                Otherwise, this resets the expressions.
2408            dialect: the dialect used to parse the input expression.
2409            copy: if `False`, modify this expression instance in-place.
2410            opts: other options to use to parse the input expressions.
2411
2412        Returns:
2413            The modified expression.
2414        """
2415        return _apply_cte_builder(
2416            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2417        )
2418
2419
2420QUERY_MODIFIERS = {
2421    "match": False,
2422    "laterals": False,
2423    "joins": False,
2424    "connect": False,
2425    "pivots": False,
2426    "where": False,
2427    "group": False,
2428    "having": False,
2429    "qualify": False,
2430    "windows": False,
2431    "distribute": False,
2432    "sort": False,
2433    "cluster": False,
2434    "order": False,
2435    "limit": False,
2436    "offset": False,
2437    "locks": False,
2438    "sample": False,
2439    "settings": False,
2440    "format": False,
2441}
2442
2443
2444# https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-ver16
2445class WithTableHint(Expression):
2446    arg_types = {"expressions": True}
2447
2448
2449# https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
2450class IndexTableHint(Expression):
2451    arg_types = {"this": True, "expressions": False, "target": False}
2452
2453
2454class Table(Expression):
2455    arg_types = {
2456        "this": True,
2457        "alias": False,
2458        "db": False,
2459        "catalog": False,
2460        "laterals": False,
2461        "joins": False,
2462        "pivots": False,
2463        "hints": False,
2464        "system_time": False,
2465        "version": False,
2466        "format": False,
2467        "pattern": False,
2468        "index": False,
2469    }
2470
2471    @property
2472    def name(self) -> str:
2473        if isinstance(self.this, Func):
2474            return ""
2475        return self.this.name
2476
2477    @property
2478    def db(self) -> str:
2479        return self.text("db")
2480
2481    @property
2482    def catalog(self) -> str:
2483        return self.text("catalog")
2484
2485    @property
2486    def selects(self) -> t.List[Expression]:
2487        return []
2488
2489    @property
2490    def named_selects(self) -> t.List[str]:
2491        return []
2492
2493    @property
2494    def parts(self) -> t.List[Expression]:
2495        """Return the parts of a table in order catalog, db, table."""
2496        parts: t.List[Expression] = []
2497
2498        for arg in ("catalog", "db", "this"):
2499            part = self.args.get(arg)
2500
2501            if isinstance(part, Dot):
2502                parts.extend(part.flatten())
2503            elif isinstance(part, Expression):
2504                parts.append(part)
2505
2506        return parts
2507
2508
2509class Union(Subqueryable):
2510    arg_types = {
2511        "with": False,
2512        "this": True,
2513        "expression": True,
2514        "distinct": False,
2515        "by_name": False,
2516        **QUERY_MODIFIERS,
2517    }
2518
2519    def limit(
2520        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2521    ) -> Select:
2522        """
2523        Set the LIMIT expression.
2524
2525        Example:
2526            >>> select("1").union(select("1")).limit(1).sql()
2527            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2528
2529        Args:
2530            expression: the SQL code string to parse.
2531                This can also be an integer.
2532                If a `Limit` instance is passed, this is used as-is.
2533                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2534            dialect: the dialect used to parse the input expression.
2535            copy: if `False`, modify this expression instance in-place.
2536            opts: other options to use to parse the input expressions.
2537
2538        Returns:
2539            The limited subqueryable.
2540        """
2541        return (
2542            select("*")
2543            .from_(self.subquery(alias="_l_0", copy=copy))
2544            .limit(expression, dialect=dialect, copy=False, **opts)
2545        )
2546
2547    def select(
2548        self,
2549        *expressions: t.Optional[ExpOrStr],
2550        append: bool = True,
2551        dialect: DialectType = None,
2552        copy: bool = True,
2553        **opts,
2554    ) -> Union:
2555        """Append to or set the SELECT of the union recursively.
2556
2557        Example:
2558            >>> from sqlglot import parse_one
2559            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2560            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2561
2562        Args:
2563            *expressions: the SQL code strings to parse.
2564                If an `Expression` instance is passed, it will be used as-is.
2565            append: if `True`, add to any existing expressions.
2566                Otherwise, this resets the expressions.
2567            dialect: the dialect used to parse the input expressions.
2568            copy: if `False`, modify this expression instance in-place.
2569            opts: other options to use to parse the input expressions.
2570
2571        Returns:
2572            Union: the modified expression.
2573        """
2574        this = self.copy() if copy else self
2575        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2576        this.expression.unnest().select(
2577            *expressions, append=append, dialect=dialect, copy=False, **opts
2578        )
2579        return this
2580
2581    @property
2582    def named_selects(self) -> t.List[str]:
2583        return self.this.unnest().named_selects
2584
2585    @property
2586    def is_star(self) -> bool:
2587        return self.this.is_star or self.expression.is_star
2588
2589    @property
2590    def selects(self) -> t.List[Expression]:
2591        return self.this.unnest().selects
2592
2593    @property
2594    def left(self):
2595        return self.this
2596
2597    @property
2598    def right(self):
2599        return self.expression
2600
2601
2602class Except(Union):
2603    pass
2604
2605
2606class Intersect(Union):
2607    pass
2608
2609
2610class Unnest(UDTF):
2611    arg_types = {
2612        "expressions": True,
2613        "alias": False,
2614        "offset": False,
2615    }
2616
2617
2618class Update(Expression):
2619    arg_types = {
2620        "with": False,
2621        "this": False,
2622        "expressions": True,
2623        "from": False,
2624        "where": False,
2625        "returning": False,
2626        "order": False,
2627        "limit": False,
2628    }
2629
2630
2631class Values(UDTF):
2632    arg_types = {
2633        "expressions": True,
2634        "ordinality": False,
2635        "alias": False,
2636    }
2637
2638
2639class Var(Expression):
2640    pass
2641
2642
2643class Version(Expression):
2644    """
2645    Time travel, iceberg, bigquery etc
2646    https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots
2647    https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html
2648    https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
2649    https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16
2650    this is either TIMESTAMP or VERSION
2651    kind is ("AS OF", "BETWEEN")
2652    """
2653
2654    arg_types = {"this": True, "kind": True, "expression": False}
2655
2656
2657class Schema(Expression):
2658    arg_types = {"this": False, "expressions": False}
2659
2660
2661# https://dev.mysql.com/doc/refman/8.0/en/select.html
2662# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html
2663class Lock(Expression):
2664    arg_types = {"update": True, "expressions": False, "wait": False}
2665
2666
2667class Select(Subqueryable):
2668    arg_types = {
2669        "with": False,
2670        "kind": False,
2671        "expressions": False,
2672        "hint": False,
2673        "distinct": False,
2674        "into": False,
2675        "from": False,
2676        **QUERY_MODIFIERS,
2677    }
2678
2679    def from_(
2680        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2681    ) -> Select:
2682        """
2683        Set the FROM expression.
2684
2685        Example:
2686            >>> Select().from_("tbl").select("x").sql()
2687            'SELECT x FROM tbl'
2688
2689        Args:
2690            expression : the SQL code strings to parse.
2691                If a `From` instance is passed, this is used as-is.
2692                If another `Expression` instance is passed, it will be wrapped in a `From`.
2693            dialect: the dialect used to parse the input expression.
2694            copy: if `False`, modify this expression instance in-place.
2695            opts: other options to use to parse the input expressions.
2696
2697        Returns:
2698            The modified Select expression.
2699        """
2700        return _apply_builder(
2701            expression=expression,
2702            instance=self,
2703            arg="from",
2704            into=From,
2705            prefix="FROM",
2706            dialect=dialect,
2707            copy=copy,
2708            **opts,
2709        )
2710
2711    def group_by(
2712        self,
2713        *expressions: t.Optional[ExpOrStr],
2714        append: bool = True,
2715        dialect: DialectType = None,
2716        copy: bool = True,
2717        **opts,
2718    ) -> Select:
2719        """
2720        Set the GROUP BY expression.
2721
2722        Example:
2723            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2724            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2725
2726        Args:
2727            *expressions: the SQL code strings to parse.
2728                If a `Group` instance is passed, this is used as-is.
2729                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2730                If nothing is passed in then a group by is not applied to the expression
2731            append: if `True`, add to any existing expressions.
2732                Otherwise, this flattens all the `Group` expression into a single expression.
2733            dialect: the dialect used to parse the input expression.
2734            copy: if `False`, modify this expression instance in-place.
2735            opts: other options to use to parse the input expressions.
2736
2737        Returns:
2738            The modified Select expression.
2739        """
2740        if not expressions:
2741            return self if not copy else self.copy()
2742
2743        return _apply_child_list_builder(
2744            *expressions,
2745            instance=self,
2746            arg="group",
2747            append=append,
2748            copy=copy,
2749            prefix="GROUP BY",
2750            into=Group,
2751            dialect=dialect,
2752            **opts,
2753        )
2754
2755    def order_by(
2756        self,
2757        *expressions: t.Optional[ExpOrStr],
2758        append: bool = True,
2759        dialect: DialectType = None,
2760        copy: bool = True,
2761        **opts,
2762    ) -> Select:
2763        """
2764        Set the ORDER BY expression.
2765
2766        Example:
2767            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2768            'SELECT x FROM tbl ORDER BY x DESC'
2769
2770        Args:
2771            *expressions: the SQL code strings to parse.
2772                If a `Group` instance is passed, this is used as-is.
2773                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2774            append: if `True`, add to any existing expressions.
2775                Otherwise, this flattens all the `Order` expression into a single expression.
2776            dialect: the dialect used to parse the input expression.
2777            copy: if `False`, modify this expression instance in-place.
2778            opts: other options to use to parse the input expressions.
2779
2780        Returns:
2781            The modified Select expression.
2782        """
2783        return _apply_child_list_builder(
2784            *expressions,
2785            instance=self,
2786            arg="order",
2787            append=append,
2788            copy=copy,
2789            prefix="ORDER BY",
2790            into=Order,
2791            dialect=dialect,
2792            **opts,
2793        )
2794
2795    def sort_by(
2796        self,
2797        *expressions: t.Optional[ExpOrStr],
2798        append: bool = True,
2799        dialect: DialectType = None,
2800        copy: bool = True,
2801        **opts,
2802    ) -> Select:
2803        """
2804        Set the SORT BY expression.
2805
2806        Example:
2807            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2808            'SELECT x FROM tbl SORT BY x DESC'
2809
2810        Args:
2811            *expressions: the SQL code strings to parse.
2812                If a `Group` instance is passed, this is used as-is.
2813                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2814            append: if `True`, add to any existing expressions.
2815                Otherwise, this flattens all the `Order` expression into a single expression.
2816            dialect: the dialect used to parse the input expression.
2817            copy: if `False`, modify this expression instance in-place.
2818            opts: other options to use to parse the input expressions.
2819
2820        Returns:
2821            The modified Select expression.
2822        """
2823        return _apply_child_list_builder(
2824            *expressions,
2825            instance=self,
2826            arg="sort",
2827            append=append,
2828            copy=copy,
2829            prefix="SORT BY",
2830            into=Sort,
2831            dialect=dialect,
2832            **opts,
2833        )
2834
2835    def cluster_by(
2836        self,
2837        *expressions: t.Optional[ExpOrStr],
2838        append: bool = True,
2839        dialect: DialectType = None,
2840        copy: bool = True,
2841        **opts,
2842    ) -> Select:
2843        """
2844        Set the CLUSTER BY expression.
2845
2846        Example:
2847            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2848            'SELECT x FROM tbl CLUSTER BY x DESC'
2849
2850        Args:
2851            *expressions: the SQL code strings to parse.
2852                If a `Group` instance is passed, this is used as-is.
2853                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2854            append: if `True`, add to any existing expressions.
2855                Otherwise, this flattens all the `Order` expression into a single expression.
2856            dialect: the dialect used to parse the input expression.
2857            copy: if `False`, modify this expression instance in-place.
2858            opts: other options to use to parse the input expressions.
2859
2860        Returns:
2861            The modified Select expression.
2862        """
2863        return _apply_child_list_builder(
2864            *expressions,
2865            instance=self,
2866            arg="cluster",
2867            append=append,
2868            copy=copy,
2869            prefix="CLUSTER BY",
2870            into=Cluster,
2871            dialect=dialect,
2872            **opts,
2873        )
2874
2875    def limit(
2876        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2877    ) -> Select:
2878        """
2879        Set the LIMIT expression.
2880
2881        Example:
2882            >>> Select().from_("tbl").select("x").limit(10).sql()
2883            'SELECT x FROM tbl LIMIT 10'
2884
2885        Args:
2886            expression: the SQL code string to parse.
2887                This can also be an integer.
2888                If a `Limit` instance is passed, this is used as-is.
2889                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2890            dialect: the dialect used to parse the input expression.
2891            copy: if `False`, modify this expression instance in-place.
2892            opts: other options to use to parse the input expressions.
2893
2894        Returns:
2895            Select: the modified expression.
2896        """
2897        return _apply_builder(
2898            expression=expression,
2899            instance=self,
2900            arg="limit",
2901            into=Limit,
2902            prefix="LIMIT",
2903            dialect=dialect,
2904            copy=copy,
2905            into_arg="expression",
2906            **opts,
2907        )
2908
2909    def offset(
2910        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2911    ) -> Select:
2912        """
2913        Set the OFFSET expression.
2914
2915        Example:
2916            >>> Select().from_("tbl").select("x").offset(10).sql()
2917            'SELECT x FROM tbl OFFSET 10'
2918
2919        Args:
2920            expression: the SQL code string to parse.
2921                This can also be an integer.
2922                If a `Offset` instance is passed, this is used as-is.
2923                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2924            dialect: the dialect used to parse the input expression.
2925            copy: if `False`, modify this expression instance in-place.
2926            opts: other options to use to parse the input expressions.
2927
2928        Returns:
2929            The modified Select expression.
2930        """
2931        return _apply_builder(
2932            expression=expression,
2933            instance=self,
2934            arg="offset",
2935            into=Offset,
2936            prefix="OFFSET",
2937            dialect=dialect,
2938            copy=copy,
2939            into_arg="expression",
2940            **opts,
2941        )
2942
2943    def select(
2944        self,
2945        *expressions: t.Optional[ExpOrStr],
2946        append: bool = True,
2947        dialect: DialectType = None,
2948        copy: bool = True,
2949        **opts,
2950    ) -> Select:
2951        """
2952        Append to or set the SELECT expressions.
2953
2954        Example:
2955            >>> Select().select("x", "y").sql()
2956            'SELECT x, y'
2957
2958        Args:
2959            *expressions: the SQL code strings to parse.
2960                If an `Expression` instance is passed, it will be used as-is.
2961            append: if `True`, add to any existing expressions.
2962                Otherwise, this resets the expressions.
2963            dialect: the dialect used to parse the input expressions.
2964            copy: if `False`, modify this expression instance in-place.
2965            opts: other options to use to parse the input expressions.
2966
2967        Returns:
2968            The modified Select expression.
2969        """
2970        return _apply_list_builder(
2971            *expressions,
2972            instance=self,
2973            arg="expressions",
2974            append=append,
2975            dialect=dialect,
2976            copy=copy,
2977            **opts,
2978        )
2979
2980    def lateral(
2981        self,
2982        *expressions: t.Optional[ExpOrStr],
2983        append: bool = True,
2984        dialect: DialectType = None,
2985        copy: bool = True,
2986        **opts,
2987    ) -> Select:
2988        """
2989        Append to or set the LATERAL expressions.
2990
2991        Example:
2992            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2993            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2994
2995        Args:
2996            *expressions: the SQL code strings to parse.
2997                If an `Expression` instance is passed, it will be used as-is.
2998            append: if `True`, add to any existing expressions.
2999                Otherwise, this resets the expressions.
3000            dialect: the dialect used to parse the input expressions.
3001            copy: if `False`, modify this expression instance in-place.
3002            opts: other options to use to parse the input expressions.
3003
3004        Returns:
3005            The modified Select expression.
3006        """
3007        return _apply_list_builder(
3008            *expressions,
3009            instance=self,
3010            arg="laterals",
3011            append=append,
3012            into=Lateral,
3013            prefix="LATERAL VIEW",
3014            dialect=dialect,
3015            copy=copy,
3016            **opts,
3017        )
3018
3019    def join(
3020        self,
3021        expression: ExpOrStr,
3022        on: t.Optional[ExpOrStr] = None,
3023        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
3024        append: bool = True,
3025        join_type: t.Optional[str] = None,
3026        join_alias: t.Optional[Identifier | str] = None,
3027        dialect: DialectType = None,
3028        copy: bool = True,
3029        **opts,
3030    ) -> Select:
3031        """
3032        Append to or set the JOIN expressions.
3033
3034        Example:
3035            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
3036            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
3037
3038            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
3039            'SELECT 1 FROM a JOIN b USING (x, y, z)'
3040
3041            Use `join_type` to change the type of join:
3042
3043            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
3044            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
3045
3046        Args:
3047            expression: the SQL code string to parse.
3048                If an `Expression` instance is passed, it will be used as-is.
3049            on: optionally specify the join "on" criteria as a SQL string.
3050                If an `Expression` instance is passed, it will be used as-is.
3051            using: optionally specify the join "using" criteria as a SQL string.
3052                If an `Expression` instance is passed, it will be used as-is.
3053            append: if `True`, add to any existing expressions.
3054                Otherwise, this resets the expressions.
3055            join_type: if set, alter the parsed join type.
3056            join_alias: an optional alias for the joined source.
3057            dialect: the dialect used to parse the input expressions.
3058            copy: if `False`, modify this expression instance in-place.
3059            opts: other options to use to parse the input expressions.
3060
3061        Returns:
3062            Select: the modified expression.
3063        """
3064        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3065
3066        try:
3067            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3068        except ParseError:
3069            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3070
3071        join = expression if isinstance(expression, Join) else Join(this=expression)
3072
3073        if isinstance(join.this, Select):
3074            join.this.replace(join.this.subquery())
3075
3076        if join_type:
3077            method: t.Optional[Token]
3078            side: t.Optional[Token]
3079            kind: t.Optional[Token]
3080
3081            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3082
3083            if method:
3084                join.set("method", method.text)
3085            if side:
3086                join.set("side", side.text)
3087            if kind:
3088                join.set("kind", kind.text)
3089
3090        if on:
3091            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3092            join.set("on", on)
3093
3094        if using:
3095            join = _apply_list_builder(
3096                *ensure_list(using),
3097                instance=join,
3098                arg="using",
3099                append=append,
3100                copy=copy,
3101                into=Identifier,
3102                **opts,
3103            )
3104
3105        if join_alias:
3106            join.set("this", alias_(join.this, join_alias, table=True))
3107
3108        return _apply_list_builder(
3109            join,
3110            instance=self,
3111            arg="joins",
3112            append=append,
3113            copy=copy,
3114            **opts,
3115        )
3116
3117    def where(
3118        self,
3119        *expressions: t.Optional[ExpOrStr],
3120        append: bool = True,
3121        dialect: DialectType = None,
3122        copy: bool = True,
3123        **opts,
3124    ) -> Select:
3125        """
3126        Append to or set the WHERE expressions.
3127
3128        Example:
3129            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3130            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3131
3132        Args:
3133            *expressions: the SQL code strings to parse.
3134                If an `Expression` instance is passed, it will be used as-is.
3135                Multiple expressions are combined with an AND operator.
3136            append: if `True`, AND the new expressions to any existing expression.
3137                Otherwise, this resets the expression.
3138            dialect: the dialect used to parse the input expressions.
3139            copy: if `False`, modify this expression instance in-place.
3140            opts: other options to use to parse the input expressions.
3141
3142        Returns:
3143            Select: the modified expression.
3144        """
3145        return _apply_conjunction_builder(
3146            *expressions,
3147            instance=self,
3148            arg="where",
3149            append=append,
3150            into=Where,
3151            dialect=dialect,
3152            copy=copy,
3153            **opts,
3154        )
3155
3156    def having(
3157        self,
3158        *expressions: t.Optional[ExpOrStr],
3159        append: bool = True,
3160        dialect: DialectType = None,
3161        copy: bool = True,
3162        **opts,
3163    ) -> Select:
3164        """
3165        Append to or set the HAVING expressions.
3166
3167        Example:
3168            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3169            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3170
3171        Args:
3172            *expressions: the SQL code strings to parse.
3173                If an `Expression` instance is passed, it will be used as-is.
3174                Multiple expressions are combined with an AND operator.
3175            append: if `True`, AND the new expressions to any existing expression.
3176                Otherwise, this resets the expression.
3177            dialect: the dialect used to parse the input expressions.
3178            copy: if `False`, modify this expression instance in-place.
3179            opts: other options to use to parse the input expressions.
3180
3181        Returns:
3182            The modified Select expression.
3183        """
3184        return _apply_conjunction_builder(
3185            *expressions,
3186            instance=self,
3187            arg="having",
3188            append=append,
3189            into=Having,
3190            dialect=dialect,
3191            copy=copy,
3192            **opts,
3193        )
3194
3195    def window(
3196        self,
3197        *expressions: t.Optional[ExpOrStr],
3198        append: bool = True,
3199        dialect: DialectType = None,
3200        copy: bool = True,
3201        **opts,
3202    ) -> Select:
3203        return _apply_list_builder(
3204            *expressions,
3205            instance=self,
3206            arg="windows",
3207            append=append,
3208            into=Window,
3209            dialect=dialect,
3210            copy=copy,
3211            **opts,
3212        )
3213
3214    def qualify(
3215        self,
3216        *expressions: t.Optional[ExpOrStr],
3217        append: bool = True,
3218        dialect: DialectType = None,
3219        copy: bool = True,
3220        **opts,
3221    ) -> Select:
3222        return _apply_conjunction_builder(
3223            *expressions,
3224            instance=self,
3225            arg="qualify",
3226            append=append,
3227            into=Qualify,
3228            dialect=dialect,
3229            copy=copy,
3230            **opts,
3231        )
3232
3233    def distinct(
3234        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3235    ) -> Select:
3236        """
3237        Set the OFFSET expression.
3238
3239        Example:
3240            >>> Select().from_("tbl").select("x").distinct().sql()
3241            'SELECT DISTINCT x FROM tbl'
3242
3243        Args:
3244            ons: the expressions to distinct on
3245            distinct: whether the Select should be distinct
3246            copy: if `False`, modify this expression instance in-place.
3247
3248        Returns:
3249            Select: the modified expression.
3250        """
3251        instance = maybe_copy(self, copy)
3252        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3253        instance.set("distinct", Distinct(on=on) if distinct else None)
3254        return instance
3255
3256    def ctas(
3257        self,
3258        table: ExpOrStr,
3259        properties: t.Optional[t.Dict] = None,
3260        dialect: DialectType = None,
3261        copy: bool = True,
3262        **opts,
3263    ) -> Create:
3264        """
3265        Convert this expression to a CREATE TABLE AS statement.
3266
3267        Example:
3268            >>> Select().select("*").from_("tbl").ctas("x").sql()
3269            'CREATE TABLE x AS SELECT * FROM tbl'
3270
3271        Args:
3272            table: the SQL code string to parse as the table name.
3273                If another `Expression` instance is passed, it will be used as-is.
3274            properties: an optional mapping of table properties
3275            dialect: the dialect used to parse the input table.
3276            copy: if `False`, modify this expression instance in-place.
3277            opts: other options to use to parse the input table.
3278
3279        Returns:
3280            The new Create expression.
3281        """
3282        instance = maybe_copy(self, copy)
3283        table_expression = maybe_parse(
3284            table,
3285            into=Table,
3286            dialect=dialect,
3287            **opts,
3288        )
3289        properties_expression = None
3290        if properties:
3291            properties_expression = Properties.from_dict(properties)
3292
3293        return Create(
3294            this=table_expression,
3295            kind="table",
3296            expression=instance,
3297            properties=properties_expression,
3298        )
3299
3300    def lock(self, update: bool = True, copy: bool = True) -> Select:
3301        """
3302        Set the locking read mode for this expression.
3303
3304        Examples:
3305            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3306            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3307
3308            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3309            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3310
3311        Args:
3312            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3313            copy: if `False`, modify this expression instance in-place.
3314
3315        Returns:
3316            The modified expression.
3317        """
3318        inst = maybe_copy(self, copy)
3319        inst.set("locks", [Lock(update=update)])
3320
3321        return inst
3322
3323    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3324        """
3325        Set hints for this expression.
3326
3327        Examples:
3328            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3329            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3330
3331        Args:
3332            hints: The SQL code strings to parse as the hints.
3333                If an `Expression` instance is passed, it will be used as-is.
3334            dialect: The dialect used to parse the hints.
3335            copy: If `False`, modify this expression instance in-place.
3336
3337        Returns:
3338            The modified expression.
3339        """
3340        inst = maybe_copy(self, copy)
3341        inst.set(
3342            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3343        )
3344
3345        return inst
3346
3347    @property
3348    def named_selects(self) -> t.List[str]:
3349        return [e.output_name for e in self.expressions if e.alias_or_name]
3350
3351    @property
3352    def is_star(self) -> bool:
3353        return any(expression.is_star for expression in self.expressions)
3354
3355    @property
3356    def selects(self) -> t.List[Expression]:
3357        return self.expressions
3358
3359
3360class Subquery(DerivedTable, Unionable):
3361    arg_types = {
3362        "this": True,
3363        "alias": False,
3364        "with": False,
3365        **QUERY_MODIFIERS,
3366    }
3367
3368    def unnest(self):
3369        """
3370        Returns the first non subquery.
3371        """
3372        expression = self
3373        while isinstance(expression, Subquery):
3374            expression = expression.this
3375        return expression
3376
3377    def unwrap(self) -> Subquery:
3378        expression = self
3379        while expression.same_parent and expression.is_wrapper:
3380            expression = t.cast(Subquery, expression.parent)
3381        return expression
3382
3383    @property
3384    def is_wrapper(self) -> bool:
3385        """
3386        Whether this Subquery acts as a simple wrapper around another expression.
3387
3388        SELECT * FROM (((SELECT * FROM t)))
3389                      ^
3390                      This corresponds to a "wrapper" Subquery node
3391        """
3392        return all(v is None for k, v in self.args.items() if k != "this")
3393
3394    @property
3395    def is_star(self) -> bool:
3396        return self.this.is_star
3397
3398    @property
3399    def output_name(self) -> str:
3400        return self.alias
3401
3402
3403class TableSample(Expression):
3404    arg_types = {
3405        "this": False,
3406        "expressions": False,
3407        "method": False,
3408        "bucket_numerator": False,
3409        "bucket_denominator": False,
3410        "bucket_field": False,
3411        "percent": False,
3412        "rows": False,
3413        "size": False,
3414        "seed": False,
3415        "kind": False,
3416    }
3417
3418
3419class Tag(Expression):
3420    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3421
3422    arg_types = {
3423        "this": False,
3424        "prefix": False,
3425        "postfix": False,
3426    }
3427
3428
3429# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax
3430# https://duckdb.org/docs/sql/statements/pivot
3431class Pivot(Expression):
3432    arg_types = {
3433        "this": False,
3434        "alias": False,
3435        "expressions": False,
3436        "field": False,
3437        "unpivot": False,
3438        "using": False,
3439        "group": False,
3440        "columns": False,
3441        "include_nulls": False,
3442    }
3443
3444
3445class Window(Condition):
3446    arg_types = {
3447        "this": True,
3448        "partition_by": False,
3449        "order": False,
3450        "spec": False,
3451        "alias": False,
3452        "over": False,
3453        "first": False,
3454    }
3455
3456
3457class WindowSpec(Expression):
3458    arg_types = {
3459        "kind": False,
3460        "start": False,
3461        "start_side": False,
3462        "end": False,
3463        "end_side": False,
3464    }
3465
3466
3467class Where(Expression):
3468    pass
3469
3470
3471class Star(Expression):
3472    arg_types = {"except": False, "replace": False}
3473
3474    @property
3475    def name(self) -> str:
3476        return "*"
3477
3478    @property
3479    def output_name(self) -> str:
3480        return self.name
3481
3482
3483class Parameter(Condition):
3484    arg_types = {"this": True, "wrapped": False}
3485
3486
3487class SessionParameter(Condition):
3488    arg_types = {"this": True, "kind": False}
3489
3490
3491class Placeholder(Condition):
3492    arg_types = {"this": False, "kind": False}
3493
3494
3495class Null(Condition):
3496    arg_types: t.Dict[str, t.Any] = {}
3497
3498    @property
3499    def name(self) -> str:
3500        return "NULL"
3501
3502
3503class Boolean(Condition):
3504    pass
3505
3506
3507class DataTypeParam(Expression):
3508    arg_types = {"this": True, "expression": False}
3509
3510
3511class DataType(Expression):
3512    arg_types = {
3513        "this": True,
3514        "expressions": False,
3515        "nested": False,
3516        "values": False,
3517        "prefix": False,
3518        "kind": False,
3519    }
3520
3521    class Type(AutoName):
3522        ARRAY = auto()
3523        BIGDECIMAL = auto()
3524        BIGINT = auto()
3525        BIGSERIAL = auto()
3526        BINARY = auto()
3527        BIT = auto()
3528        BOOLEAN = auto()
3529        CHAR = auto()
3530        DATE = auto()
3531        DATEMULTIRANGE = auto()
3532        DATERANGE = auto()
3533        DATETIME = auto()
3534        DATETIME64 = auto()
3535        DECIMAL = auto()
3536        DOUBLE = auto()
3537        ENUM = auto()
3538        ENUM8 = auto()
3539        ENUM16 = auto()
3540        FIXEDSTRING = auto()
3541        FLOAT = auto()
3542        GEOGRAPHY = auto()
3543        GEOMETRY = auto()
3544        HLLSKETCH = auto()
3545        HSTORE = auto()
3546        IMAGE = auto()
3547        INET = auto()
3548        INT = auto()
3549        INT128 = auto()
3550        INT256 = auto()
3551        INT4MULTIRANGE = auto()
3552        INT4RANGE = auto()
3553        INT8MULTIRANGE = auto()
3554        INT8RANGE = auto()
3555        INTERVAL = auto()
3556        IPADDRESS = auto()
3557        IPPREFIX = auto()
3558        JSON = auto()
3559        JSONB = auto()
3560        LONGBLOB = auto()
3561        LONGTEXT = auto()
3562        LOWCARDINALITY = auto()
3563        MAP = auto()
3564        MEDIUMBLOB = auto()
3565        MEDIUMINT = auto()
3566        MEDIUMTEXT = auto()
3567        MONEY = auto()
3568        NCHAR = auto()
3569        NESTED = auto()
3570        NULL = auto()
3571        NULLABLE = auto()
3572        NUMMULTIRANGE = auto()
3573        NUMRANGE = auto()
3574        NVARCHAR = auto()
3575        OBJECT = auto()
3576        ROWVERSION = auto()
3577        SERIAL = auto()
3578        SET = auto()
3579        SMALLINT = auto()
3580        SMALLMONEY = auto()
3581        SMALLSERIAL = auto()
3582        STRUCT = auto()
3583        SUPER = auto()
3584        TEXT = auto()
3585        TINYBLOB = auto()
3586        TINYTEXT = auto()
3587        TIME = auto()
3588        TIMETZ = auto()
3589        TIMESTAMP = auto()
3590        TIMESTAMPLTZ = auto()
3591        TIMESTAMPTZ = auto()
3592        TINYINT = auto()
3593        TSMULTIRANGE = auto()
3594        TSRANGE = auto()
3595        TSTZMULTIRANGE = auto()
3596        TSTZRANGE = auto()
3597        UBIGINT = auto()
3598        UINT = auto()
3599        UINT128 = auto()
3600        UINT256 = auto()
3601        UMEDIUMINT = auto()
3602        UDECIMAL = auto()
3603        UNIQUEIDENTIFIER = auto()
3604        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3605        USERDEFINED = "USER-DEFINED"
3606        USMALLINT = auto()
3607        UTINYINT = auto()
3608        UUID = auto()
3609        VARBINARY = auto()
3610        VARCHAR = auto()
3611        VARIANT = auto()
3612        XML = auto()
3613        YEAR = auto()
3614
3615    TEXT_TYPES = {
3616        Type.CHAR,
3617        Type.NCHAR,
3618        Type.VARCHAR,
3619        Type.NVARCHAR,
3620        Type.TEXT,
3621    }
3622
3623    INTEGER_TYPES = {
3624        Type.INT,
3625        Type.TINYINT,
3626        Type.SMALLINT,
3627        Type.BIGINT,
3628        Type.INT128,
3629        Type.INT256,
3630    }
3631
3632    FLOAT_TYPES = {
3633        Type.FLOAT,
3634        Type.DOUBLE,
3635    }
3636
3637    NUMERIC_TYPES = {
3638        *INTEGER_TYPES,
3639        *FLOAT_TYPES,
3640    }
3641
3642    TEMPORAL_TYPES = {
3643        Type.TIME,
3644        Type.TIMETZ,
3645        Type.TIMESTAMP,
3646        Type.TIMESTAMPTZ,
3647        Type.TIMESTAMPLTZ,
3648        Type.DATE,
3649        Type.DATETIME,
3650        Type.DATETIME64,
3651    }
3652
3653    @classmethod
3654    def build(
3655        cls,
3656        dtype: str | DataType | DataType.Type,
3657        dialect: DialectType = None,
3658        udt: bool = False,
3659        **kwargs,
3660    ) -> DataType:
3661        """
3662        Constructs a DataType object.
3663
3664        Args:
3665            dtype: the data type of interest.
3666            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3667            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3668                DataType, thus creating a user-defined type.
3669            kawrgs: additional arguments to pass in the constructor of DataType.
3670
3671        Returns:
3672            The constructed DataType object.
3673        """
3674        from sqlglot import parse_one
3675
3676        if isinstance(dtype, str):
3677            if dtype.upper() == "UNKNOWN":
3678                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3679
3680            try:
3681                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3682            except ParseError:
3683                if udt:
3684                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3685                raise
3686        elif isinstance(dtype, DataType.Type):
3687            data_type_exp = DataType(this=dtype)
3688        elif isinstance(dtype, DataType):
3689            return dtype
3690        else:
3691            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3692
3693        return DataType(**{**data_type_exp.args, **kwargs})
3694
3695    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3696        """
3697        Checks whether this DataType matches one of the provided data types. Nested types or precision
3698        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3699
3700        Args:
3701            dtypes: the data types to compare this DataType to.
3702
3703        Returns:
3704            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3705        """
3706        for dtype in dtypes:
3707            other = DataType.build(dtype, udt=True)
3708
3709            if (
3710                other.expressions
3711                or self.this == DataType.Type.USERDEFINED
3712                or other.this == DataType.Type.USERDEFINED
3713            ):
3714                matches = self == other
3715            else:
3716                matches = self.this == other.this
3717
3718            if matches:
3719                return True
3720        return False
3721
3722
3723# https://www.postgresql.org/docs/15/datatype-pseudo.html
3724class PseudoType(DataType):
3725    arg_types = {"this": True}
3726
3727
3728# https://www.postgresql.org/docs/15/datatype-oid.html
3729class ObjectIdentifier(DataType):
3730    arg_types = {"this": True}
3731
3732
3733# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3734class SubqueryPredicate(Predicate):
3735    pass
3736
3737
3738class All(SubqueryPredicate):
3739    pass
3740
3741
3742class Any(SubqueryPredicate):
3743    pass
3744
3745
3746class Exists(SubqueryPredicate):
3747    pass
3748
3749
3750# Commands to interact with the databases or engines. For most of the command
3751# expressions we parse whatever comes after the command's name as a string.
3752class Command(Expression):
3753    arg_types = {"this": True, "expression": False}
3754
3755
3756class Transaction(Expression):
3757    arg_types = {"this": False, "modes": False, "mark": False}
3758
3759
3760class Commit(Expression):
3761    arg_types = {"chain": False, "this": False, "durability": False}
3762
3763
3764class Rollback(Expression):
3765    arg_types = {"savepoint": False, "this": False}
3766
3767
3768class AlterTable(Expression):
3769    arg_types = {"this": True, "actions": True, "exists": False, "only": False}
3770
3771
3772class AddConstraint(Expression):
3773    arg_types = {"this": False, "expression": False, "enforced": False}
3774
3775
3776class DropPartition(Expression):
3777    arg_types = {"expressions": True, "exists": False}
3778
3779
3780# Binary expressions like (ADD a b)
3781class Binary(Condition):
3782    arg_types = {"this": True, "expression": True}
3783
3784    @property
3785    def left(self):
3786        return self.this
3787
3788    @property
3789    def right(self):
3790        return self.expression
3791
3792
3793class Add(Binary):
3794    pass
3795
3796
3797class Connector(Binary):
3798    pass
3799
3800
3801class And(Connector):
3802    pass
3803
3804
3805class Or(Connector):
3806    pass
3807
3808
3809class BitwiseAnd(Binary):
3810    pass
3811
3812
3813class BitwiseLeftShift(Binary):
3814    pass
3815
3816
3817class BitwiseOr(Binary):
3818    pass
3819
3820
3821class BitwiseRightShift(Binary):
3822    pass
3823
3824
3825class BitwiseXor(Binary):
3826    pass
3827
3828
3829class Div(Binary):
3830    pass
3831
3832
3833class Overlaps(Binary):
3834    pass
3835
3836
3837class Dot(Binary):
3838    @property
3839    def name(self) -> str:
3840        return self.expression.name
3841
3842    @property
3843    def output_name(self) -> str:
3844        return self.name
3845
3846    @classmethod
3847    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3848        """Build a Dot object with a sequence of expressions."""
3849        if len(expressions) < 2:
3850            raise ValueError(f"Dot requires >= 2 expressions.")
3851
3852        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))
3853
3854
3855class DPipe(Binary):
3856    pass
3857
3858
3859class SafeDPipe(DPipe):
3860    pass
3861
3862
3863class EQ(Binary, Predicate):
3864    pass
3865
3866
3867class NullSafeEQ(Binary, Predicate):
3868    pass
3869
3870
3871class NullSafeNEQ(Binary, Predicate):
3872    pass
3873
3874
3875class Distance(Binary):
3876    pass
3877
3878
3879class Escape(Binary):
3880    pass
3881
3882
3883class Glob(Binary, Predicate):
3884    pass
3885
3886
3887class GT(Binary, Predicate):
3888    pass
3889
3890
3891class GTE(Binary, Predicate):
3892    pass
3893
3894
3895class ILike(Binary, Predicate):
3896    pass
3897
3898
3899class ILikeAny(Binary, Predicate):
3900    pass
3901
3902
3903class IntDiv(Binary):
3904    pass
3905
3906
3907class Is(Binary, Predicate):
3908    pass
3909
3910
3911class Kwarg(Binary):
3912    """Kwarg in special functions like func(kwarg => y)."""
3913
3914
3915class Like(Binary, Predicate):
3916    pass
3917
3918
3919class LikeAny(Binary, Predicate):
3920    pass
3921
3922
3923class LT(Binary, Predicate):
3924    pass
3925
3926
3927class LTE(Binary, Predicate):
3928    pass
3929
3930
3931class Mod(Binary):
3932    pass
3933
3934
3935class Mul(Binary):
3936    pass
3937
3938
3939class NEQ(Binary, Predicate):
3940    pass
3941
3942
3943class SimilarTo(Binary, Predicate):
3944    pass
3945
3946
3947class Slice(Binary):
3948    arg_types = {"this": False, "expression": False}
3949
3950
3951class Sub(Binary):
3952    pass
3953
3954
3955class ArrayOverlaps(Binary):
3956    pass
3957
3958
3959# Unary Expressions
3960# (NOT a)
3961class Unary(Condition):
3962    pass
3963
3964
3965class BitwiseNot(Unary):
3966    pass
3967
3968
3969class Not(Unary):
3970    pass
3971
3972
3973class Paren(Unary):
3974    arg_types = {"this": True, "with": False}
3975
3976    @property
3977    def output_name(self) -> str:
3978        return self.this.name
3979
3980
3981class Neg(Unary):
3982    pass
3983
3984
3985class Alias(Expression):
3986    arg_types = {"this": True, "alias": False}
3987
3988    @property
3989    def output_name(self) -> str:
3990        return self.alias
3991
3992
3993class Aliases(Expression):
3994    arg_types = {"this": True, "expressions": True}
3995
3996    @property
3997    def aliases(self):
3998        return self.expressions
3999
4000
4001class AtTimeZone(Expression):
4002    arg_types = {"this": True, "zone": True}
4003
4004
4005class Between(Predicate):
4006    arg_types = {"this": True, "low": True, "high": True}
4007
4008
4009class Bracket(Condition):
4010    arg_types = {"this": True, "expressions": True}
4011
4012    @property
4013    def output_name(self) -> str:
4014        if len(self.expressions) == 1:
4015            return self.expressions[0].output_name
4016
4017        return super().output_name
4018
4019
4020class SafeBracket(Bracket):
4021    """Represents array lookup where OOB index yields NULL instead of causing a failure."""
4022
4023
4024class Distinct(Expression):
4025    arg_types = {"expressions": False, "on": False}
4026
4027
4028class In(Predicate):
4029    arg_types = {
4030        "this": True,
4031        "expressions": False,
4032        "query": False,
4033        "unnest": False,
4034        "field": False,
4035        "is_global": False,
4036    }
4037
4038
4039class TimeUnit(Expression):
4040    """Automatically converts unit arg into a var."""
4041
4042    arg_types = {"unit": False}
4043
4044    def __init__(self, **args):
4045        unit = args.get("unit")
4046        if isinstance(unit, (Column, Literal)):
4047            args["unit"] = Var(this=unit.name)
4048        elif isinstance(unit, Week):
4049            unit.set("this", Var(this=unit.this.name))
4050
4051        super().__init__(**args)
4052
4053    @property
4054    def unit(self) -> t.Optional[Var]:
4055        return self.args.get("unit")
4056
4057
4058class IntervalOp(TimeUnit):
4059    arg_types = {"unit": True, "expression": True}
4060
4061    def interval(self):
4062        return Interval(
4063            this=self.expression.copy(),
4064            unit=self.unit.copy(),
4065        )
4066
4067
4068# https://www.oracletutorial.com/oracle-basics/oracle-interval/
4069# https://trino.io/docs/current/language/types.html#interval-day-to-second
4070# https://docs.databricks.com/en/sql/language-manual/data-types/interval-type.html
4071class IntervalSpan(DataType):
4072    arg_types = {"this": True, "expression": True}
4073
4074
4075class Interval(TimeUnit):
4076    arg_types = {"this": False, "unit": False}
4077
4078
4079class IgnoreNulls(Expression):
4080    pass
4081
4082
4083class RespectNulls(Expression):
4084    pass
4085
4086
4087# Functions
4088class Func(Condition):
4089    """
4090    The base class for all function expressions.
4091
4092    Attributes:
4093        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4094            treated as a variable length argument and the argument's value will be stored as a list.
4095        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4096            for this function expression. These values are used to map this node to a name during parsing
4097            as well as to provide the function's name during SQL string generation. By default the SQL
4098            name is set to the expression's class name transformed to snake case.
4099    """
4100
4101    is_var_len_args = False
4102
4103    @classmethod
4104    def from_arg_list(cls, args):
4105        if cls.is_var_len_args:
4106            all_arg_keys = list(cls.arg_types)
4107            # If this function supports variable length argument treat the last argument as such.
4108            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4109            num_non_var = len(non_var_len_arg_keys)
4110
4111            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4112            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4113        else:
4114            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4115
4116        return cls(**args_dict)
4117
4118    @classmethod
4119    def sql_names(cls):
4120        if cls is Func:
4121            raise NotImplementedError(
4122                "SQL name is only supported by concrete function implementations"
4123            )
4124        if "_sql_names" not in cls.__dict__:
4125            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4126        return cls._sql_names
4127
4128    @classmethod
4129    def sql_name(cls):
4130        return cls.sql_names()[0]
4131
4132    @classmethod
4133    def default_parser_mappings(cls):
4134        return {name: cls.from_arg_list for name in cls.sql_names()}
4135
4136
4137class AggFunc(Func):
4138    pass
4139
4140
4141class ParameterizedAgg(AggFunc):
4142    arg_types = {"this": True, "expressions": True, "params": True}
4143
4144
4145class Abs(Func):
4146    pass
4147
4148
4149# https://spark.apache.org/docs/latest/api/sql/index.html#transform
4150class Transform(Func):
4151    arg_types = {"this": True, "expression": True}
4152
4153
4154class Anonymous(Func):
4155    arg_types = {"this": True, "expressions": False}
4156    is_var_len_args = True
4157
4158
4159# https://docs.snowflake.com/en/sql-reference/functions/hll
4160# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
4161class Hll(AggFunc):
4162    arg_types = {"this": True, "expressions": False}
4163    is_var_len_args = True
4164
4165
4166class ApproxDistinct(AggFunc):
4167    arg_types = {"this": True, "accuracy": False}
4168    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
4169
4170
4171class Array(Func):
4172    arg_types = {"expressions": False}
4173    is_var_len_args = True
4174
4175
4176# https://docs.snowflake.com/en/sql-reference/functions/to_char
4177class ToChar(Func):
4178    arg_types = {"this": True, "format": False}
4179
4180
4181class GenerateSeries(Func):
4182    arg_types = {"start": True, "end": True, "step": False}
4183
4184
4185class ArrayAgg(AggFunc):
4186    pass
4187
4188
4189class ArrayAll(Func):
4190    arg_types = {"this": True, "expression": True}
4191
4192
4193class ArrayAny(Func):
4194    arg_types = {"this": True, "expression": True}
4195
4196
4197class ArrayConcat(Func):
4198    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4199    arg_types = {"this": True, "expressions": False}
4200    is_var_len_args = True
4201
4202
4203class ArrayContains(Binary, Func):
4204    pass
4205
4206
4207class ArrayContained(Binary):
4208    pass
4209
4210
4211class ArrayFilter(Func):
4212    arg_types = {"this": True, "expression": True}
4213    _sql_names = ["FILTER", "ARRAY_FILTER"]
4214
4215
4216class ArrayJoin(Func):
4217    arg_types = {"this": True, "expression": True, "null": False}
4218
4219
4220class ArraySize(Func):
4221    arg_types = {"this": True, "expression": False}
4222
4223
4224class ArraySort(Func):
4225    arg_types = {"this": True, "expression": False}
4226
4227
4228class ArraySum(Func):
4229    pass
4230
4231
4232class ArrayUnionAgg(AggFunc):
4233    pass
4234
4235
4236class Avg(AggFunc):
4237    pass
4238
4239
4240class AnyValue(AggFunc):
4241    arg_types = {"this": True, "having": False, "max": False, "ignore_nulls": False}
4242
4243
4244class First(Func):
4245    arg_types = {"this": True, "ignore_nulls": False}
4246
4247
4248class Last(Func):
4249    arg_types = {"this": True, "ignore_nulls": False}
4250
4251
4252class Case(Func):
4253    arg_types = {"this": False, "ifs": True, "default": False}
4254
4255    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4256        instance = maybe_copy(self, copy)
4257        instance.append(
4258            "ifs",
4259            If(
4260                this=maybe_parse(condition, copy=copy, **opts),
4261                true=maybe_parse(then, copy=copy, **opts),
4262            ),
4263        )
4264        return instance
4265
4266    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4267        instance = maybe_copy(self, copy)
4268        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4269        return instance
4270
4271
4272class Cast(Func):
4273    arg_types = {"this": True, "to": True, "format": False}
4274
4275    @property
4276    def name(self) -> str:
4277        return self.this.name
4278
4279    @property
4280    def to(self) -> DataType:
4281        return self.args["to"]
4282
4283    @property
4284    def output_name(self) -> str:
4285        return self.name
4286
4287    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4288        """
4289        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4290        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4291        array<int> != array<float>.
4292
4293        Args:
4294            dtypes: the data types to compare this Cast's DataType to.
4295
4296        Returns:
4297            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4298        """
4299        return self.to.is_type(*dtypes)
4300
4301
4302class TryCast(Cast):
4303    pass
4304
4305
4306class CastToStrType(Func):
4307    arg_types = {"this": True, "to": True}
4308
4309
4310class Collate(Binary, Func):
4311    pass
4312
4313
4314class Ceil(Func):
4315    arg_types = {"this": True, "decimals": False}
4316    _sql_names = ["CEIL", "CEILING"]
4317
4318
4319class Coalesce(Func):
4320    arg_types = {"this": True, "expressions": False}
4321    is_var_len_args = True
4322    _sql_names = ["COALESCE", "IFNULL", "NVL"]
4323
4324
4325class Chr(Func):
4326    arg_types = {"this": True, "charset": False, "expressions": False}
4327    is_var_len_args = True
4328    _sql_names = ["CHR", "CHAR"]
4329
4330
4331class Concat(Func):
4332    arg_types = {"expressions": True}
4333    is_var_len_args = True
4334
4335
4336class SafeConcat(Concat):
4337    pass
4338
4339
4340class ConcatWs(Concat):
4341    _sql_names = ["CONCAT_WS"]
4342
4343
4344class Count(AggFunc):
4345    arg_types = {"this": False, "expressions": False}
4346    is_var_len_args = True
4347
4348
4349class CountIf(AggFunc):
4350    pass
4351
4352
4353class CurrentDate(Func):
4354    arg_types = {"this": False}
4355
4356
4357class CurrentDatetime(Func):
4358    arg_types = {"this": False}
4359
4360
4361class CurrentTime(Func):
4362    arg_types = {"this": False}
4363
4364
4365class CurrentTimestamp(Func):
4366    arg_types = {"this": False}
4367
4368
4369class CurrentUser(Func):
4370    arg_types = {"this": False}
4371
4372
4373class DateAdd(Func, IntervalOp):
4374    arg_types = {"this": True, "expression": True, "unit": False}
4375
4376
4377class DateSub(Func, IntervalOp):
4378    arg_types = {"this": True, "expression": True, "unit": False}
4379
4380
4381class DateDiff(Func, TimeUnit):
4382    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4383    arg_types = {"this": True, "expression": True, "unit": False}
4384
4385
4386class DateTrunc(Func):
4387    arg_types = {"unit": True, "this": True, "zone": False}
4388
4389    @property
4390    def unit(self) -> Expression:
4391        return self.args["unit"]
4392
4393
4394class DatetimeAdd(Func, IntervalOp):
4395    arg_types = {"this": True, "expression": True, "unit": False}
4396
4397
4398class DatetimeSub(Func, IntervalOp):
4399    arg_types = {"this": True, "expression": True, "unit": False}
4400
4401
4402class DatetimeDiff(Func, TimeUnit):
4403    arg_types = {"this": True, "expression": True, "unit": False}
4404
4405
4406class DatetimeTrunc(Func, TimeUnit):
4407    arg_types = {"this": True, "unit": True, "zone": False}
4408
4409
4410class DayOfWeek(Func):
4411    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
4412
4413
4414class DayOfMonth(Func):
4415    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
4416
4417
4418class DayOfYear(Func):
4419    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
4420
4421
4422class ToDays(Func):
4423    pass
4424
4425
4426class WeekOfYear(Func):
4427    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
4428
4429
4430class MonthsBetween(Func):
4431    arg_types = {"this": True, "expression": True, "roundoff": False}
4432
4433
4434class LastDateOfMonth(Func):
4435    pass
4436
4437
4438class Extract(Func):
4439    arg_types = {"this": True, "expression": True}
4440
4441
4442class Timestamp(Func):
4443    arg_types = {"this": False, "expression": False}
4444
4445
4446class TimestampAdd(Func, TimeUnit):
4447    arg_types = {"this": True, "expression": True, "unit": False}
4448
4449
4450class TimestampSub(Func, TimeUnit):
4451    arg_types = {"this": True, "expression": True, "unit": False}
4452
4453
4454class TimestampDiff(Func, TimeUnit):
4455    arg_types = {"this": True, "expression": True, "unit": False}
4456
4457
4458class TimestampTrunc(Func, TimeUnit):
4459    arg_types = {"this": True, "unit": True, "zone": False}
4460
4461
4462class TimeAdd(Func, TimeUnit):
4463    arg_types = {"this": True, "expression": True, "unit": False}
4464
4465
4466class TimeSub(Func, TimeUnit):
4467    arg_types = {"this": True, "expression": True, "unit": False}
4468
4469
4470class TimeDiff(Func, TimeUnit):
4471    arg_types = {"this": True, "expression": True, "unit": False}
4472
4473
4474class TimeTrunc(Func, TimeUnit):
4475    arg_types = {"this": True, "unit": True, "zone": False}
4476
4477
4478class DateFromParts(Func):
4479    _sql_names = ["DATEFROMPARTS"]
4480    arg_types = {"year": True, "month": True, "day": True}
4481
4482
4483class DateStrToDate(Func):
4484    pass
4485
4486
4487class DateToDateStr(Func):
4488    pass
4489
4490
4491class DateToDi(Func):
4492    pass
4493
4494
4495# https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date
4496class Date(Func):
4497    arg_types = {"this": False, "zone": False, "expressions": False}
4498    is_var_len_args = True
4499
4500
4501class Day(Func):
4502    pass
4503
4504
4505class Decode(Func):
4506    arg_types = {"this": True, "charset": True, "replace": False}
4507
4508
4509class DiToDate(Func):
4510    pass
4511
4512
4513class Encode(Func):
4514    arg_types = {"this": True, "charset": True}
4515
4516
4517class Exp(Func):
4518    pass
4519
4520
4521class Explode(Func):
4522    pass
4523
4524
4525class Floor(Func):
4526    arg_types = {"this": True, "decimals": False}
4527
4528
4529class FromBase64(Func):
4530    pass
4531
4532
4533class ToBase64(Func):
4534    pass
4535
4536
4537class Greatest(Func):
4538    arg_types = {"this": True, "expressions": False}
4539    is_var_len_args = True
4540
4541
4542class GroupConcat(AggFunc):
4543    arg_types = {"this": True, "separator": False}
4544
4545
4546class Hex(Func):
4547    pass
4548
4549
4550class Xor(Connector, Func):
4551    arg_types = {"this": False, "expression": False, "expressions": False}
4552
4553
4554class If(Func):
4555    arg_types = {"this": True, "true": True, "false": False}
4556
4557
4558class Initcap(Func):
4559    arg_types = {"this": True, "expression": False}
4560
4561
4562class IsNan(Func):
4563    _sql_names = ["IS_NAN", "ISNAN"]
4564
4565
4566class FormatJson(Expression):
4567    pass
4568
4569
4570class JSONKeyValue(Expression):
4571    arg_types = {"this": True, "expression": True}
4572
4573
4574class JSONObject(Func):
4575    arg_types = {
4576        "expressions": False,
4577        "null_handling": False,
4578        "unique_keys": False,
4579        "return_type": False,
4580        "encoding": False,
4581    }
4582
4583
4584# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/JSON_ARRAY.html
4585class JSONArray(Func):
4586    arg_types = {
4587        "expressions": True,
4588        "null_handling": False,
4589        "return_type": False,
4590        "strict": False,
4591    }
4592
4593
4594# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/JSON_ARRAYAGG.html
4595class JSONArrayAgg(Func):
4596    arg_types = {
4597        "this": True,
4598        "order": False,
4599        "null_handling": False,
4600        "return_type": False,
4601        "strict": False,
4602    }
4603
4604
4605# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/JSON_TABLE.html
4606# Note: parsing of JSON column definitions is currently incomplete.
4607class JSONColumnDef(Expression):
4608    arg_types = {"this": True, "kind": False, "path": False}
4609
4610
4611# # https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/JSON_TABLE.html
4612class JSONTable(Func):
4613    arg_types = {
4614        "this": True,
4615        "expressions": True,
4616        "path": False,
4617        "error_handling": False,
4618        "empty_handling": False,
4619    }
4620
4621
4622class OpenJSONColumnDef(Expression):
4623    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
4624
4625
4626class OpenJSON(Func):
4627    arg_types = {"this": True, "path": False, "expressions": False}
4628
4629
4630class JSONBContains(Binary):
4631    _sql_names = ["JSONB_CONTAINS"]
4632
4633
4634class JSONExtract(Binary, Func):
4635    _sql_names = ["JSON_EXTRACT"]
4636
4637
4638class JSONExtractScalar(JSONExtract):
4639    _sql_names = ["JSON_EXTRACT_SCALAR"]
4640
4641
4642class JSONBExtract(JSONExtract):
4643    _sql_names = ["JSONB_EXTRACT"]
4644
4645
4646class JSONBExtractScalar(JSONExtract):
4647    _sql_names = ["JSONB_EXTRACT_SCALAR"]
4648
4649
4650class JSONFormat(Func):
4651    arg_types = {"this": False, "options": False}
4652    _sql_names = ["JSON_FORMAT"]
4653
4654
4655# https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_member-of
4656class JSONArrayContains(Binary, Predicate, Func):
4657    _sql_names = ["JSON_ARRAY_CONTAINS"]
4658
4659
4660class ParseJSON(Func):
4661    # BigQuery, Snowflake have PARSE_JSON, Presto has JSON_PARSE
4662    _sql_names = ["PARSE_JSON", "JSON_PARSE"]
4663
4664
4665class Least(Func):
4666    arg_types = {"this": True, "expressions": False}
4667    is_var_len_args = True
4668
4669
4670class Left(Func):
4671    arg_types = {"this": True, "expression": True}
4672
4673
4674class Right(Func):
4675    arg_types = {"this": True, "expression": True}
4676
4677
4678class Length(Func):
4679    _sql_names = ["LENGTH", "LEN"]
4680
4681
4682class Levenshtein(Func):
4683    arg_types = {
4684        "this": True,
4685        "expression": False,
4686        "ins_cost": False,
4687        "del_cost": False,
4688        "sub_cost": False,
4689    }
4690
4691
4692class Ln(Func):
4693    pass
4694
4695
4696class Log(Func):
4697    arg_types = {"this": True, "expression": False}
4698
4699
4700class Log2(Func):
4701    pass
4702
4703
4704class Log10(Func):
4705    pass
4706
4707
4708class LogicalOr(AggFunc):
4709    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
4710
4711
4712class LogicalAnd(AggFunc):
4713    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
4714
4715
4716class Lower(Func):
4717    _sql_names = ["LOWER", "LCASE"]
4718
4719
4720class Map(Func):
4721    arg_types = {"keys": False, "values": False}
4722
4723
4724class MapFromEntries(Func):
4725    pass
4726
4727
4728class StarMap(Func):
4729    pass
4730
4731
4732class VarMap(Func):
4733    arg_types = {"keys": True, "values": True}
4734    is_var_len_args = True
4735
4736    @property
4737    def keys(self) -> t.List[Expression]:
4738        return self.args["keys"].expressions
4739
4740    @property
4741    def values(self) -> t.List[Expression]:
4742        return self.args["values"].expressions
4743
4744
4745# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4746class MatchAgainst(Func):
4747    arg_types = {"this": True, "expressions": True, "modifier": False}
4748
4749
4750class Max(AggFunc):
4751    arg_types = {"this": True, "expressions": False}
4752    is_var_len_args = True
4753
4754
4755class MD5(Func):
4756    _sql_names = ["MD5"]
4757
4758
4759# Represents the variant of the MD5 function that returns a binary value
4760class MD5Digest(Func):
4761    _sql_names = ["MD5_DIGEST"]
4762
4763
4764class Min(AggFunc):
4765    arg_types = {"this": True, "expressions": False}
4766    is_var_len_args = True
4767
4768
4769class Month(Func):
4770    pass
4771
4772
4773class Nvl2(Func):
4774    arg_types = {"this": True, "true": True, "false": False}
4775
4776
4777class Posexplode(Func):
4778    pass
4779
4780
4781# https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-predict#mlpredict_function
4782class Predict(Func):
4783    arg_types = {"this": True, "expression": True, "params_struct": False}
4784
4785
4786class Pow(Binary, Func):
4787    _sql_names = ["POWER", "POW"]
4788
4789
4790class PercentileCont(AggFunc):
4791    arg_types = {"this": True, "expression": False}
4792
4793
4794class PercentileDisc(AggFunc):
4795    arg_types = {"this": True, "expression": False}
4796
4797
4798class Quantile(AggFunc):
4799    arg_types = {"this": True, "quantile": True}
4800
4801
4802class ApproxQuantile(Quantile):
4803    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4804
4805
4806class RangeN(Func):
4807    arg_types = {"this": True, "expressions": True, "each": False}
4808
4809
4810class ReadCSV(Func):
4811    _sql_names = ["READ_CSV"]
4812    is_var_len_args = True
4813    arg_types = {"this": True, "expressions": False}
4814
4815
4816class Reduce(Func):
4817    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4818
4819
4820class RegexpExtract(Func):
4821    arg_types = {
4822        "this": True,
4823        "expression": True,
4824        "position": False,
4825        "occurrence": False,
4826        "parameters": False,
4827        "group": False,
4828    }
4829
4830
4831class RegexpReplace(Func):
4832    arg_types = {
4833        "this": True,
4834        "expression": True,
4835        "replacement": True,
4836        "position": False,
4837        "occurrence": False,
4838        "parameters": False,
4839    }
4840
4841
4842class RegexpLike(Binary, Func):
4843    arg_types = {"this": True, "expression": True, "flag": False}
4844
4845
4846class RegexpILike(Func):
4847    arg_types = {"this": True, "expression": True, "flag": False}
4848
4849
4850# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4851# limit is the number of times a pattern is applied
4852class RegexpSplit(Func):
4853    arg_types = {"this": True, "expression": True, "limit": False}
4854
4855
4856class Repeat(Func):
4857    arg_types = {"this": True, "times": True}
4858
4859
4860class Round(Func):
4861    arg_types = {"this": True, "decimals": False}
4862
4863
4864class RowNumber(Func):
4865    arg_types: t.Dict[str, t.Any] = {}
4866
4867
4868class SafeDivide(Func):
4869    arg_types = {"this": True, "expression": True}
4870
4871
4872class SetAgg(AggFunc):
4873    pass
4874
4875
4876class SHA(Func):
4877    _sql_names = ["SHA", "SHA1"]
4878
4879
4880class SHA2(Func):
4881    _sql_names = ["SHA2"]
4882    arg_types = {"this": True, "length": False}
4883
4884
4885class SortArray(Func):
4886    arg_types = {"this": True, "asc": False}
4887
4888
4889class Split(Func):
4890    arg_types = {"this": True, "expression": True, "limit": False}
4891
4892
4893# Start may be omitted in the case of postgres
4894# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4895class Substring(Func):
4896    arg_types = {"this": True, "start": False, "length": False}
4897
4898
4899class StandardHash(Func):
4900    arg_types = {"this": True, "expression": False}
4901
4902
4903class StartsWith(Func):
4904    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4905    arg_types = {"this": True, "expression": True}
4906
4907
4908class StrPosition(Func):
4909    arg_types = {
4910        "this": True,
4911        "substr": True,
4912        "position": False,
4913        "instance": False,
4914    }
4915
4916
4917class StrToDate(Func):
4918    arg_types = {"this": True, "format": True}
4919
4920
4921class StrToTime(Func):
4922    arg_types = {"this": True, "format": True, "zone": False}
4923
4924
4925# Spark allows unix_timestamp()
4926# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4927class StrToUnix(Func):
4928    arg_types = {"this": False, "format": False}
4929
4930
4931# https://prestodb.io/docs/current/functions/string.html
4932# https://spark.apache.org/docs/latest/api/sql/index.html#str_to_map
4933class StrToMap(Func):
4934    arg_types = {
4935        "this": True,
4936        "pair_delim": False,
4937        "key_value_delim": False,
4938        "duplicate_resolution_callback": False,
4939    }
4940
4941
4942class NumberToStr(Func):
4943    arg_types = {"this": True, "format": True, "culture": False}
4944
4945
4946class FromBase(Func):
4947    arg_types = {"this": True, "expression": True}
4948
4949
4950class Struct(Func):
4951    arg_types = {"expressions": True}
4952    is_var_len_args = True
4953
4954
4955class StructExtract(Func):
4956    arg_types = {"this": True, "expression": True}
4957
4958
4959# https://learn.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql?view=sql-server-ver16
4960# https://docs.snowflake.com/en/sql-reference/functions/insert
4961class Stuff(Func):
4962    _sql_names = ["STUFF", "INSERT"]
4963    arg_types = {"this": True, "start": True, "length": True, "expression": True}
4964
4965
4966class Sum(AggFunc):
4967    pass
4968
4969
4970class Sqrt(Func):
4971    pass
4972
4973
4974class Stddev(AggFunc):
4975    pass
4976
4977
4978class StddevPop(AggFunc):
4979    pass
4980
4981
4982class StddevSamp(AggFunc):
4983    pass
4984
4985
4986class TimeToStr(Func):
4987    arg_types = {"this": True, "format": True, "culture": False}
4988
4989
4990class TimeToTimeStr(Func):
4991    pass
4992
4993
4994class TimeToUnix(Func):
4995    pass
4996
4997
4998class TimeStrToDate(Func):
4999    pass
5000
5001
5002class TimeStrToTime(Func):
5003    pass
5004
5005
5006class TimeStrToUnix(Func):
5007    pass
5008
5009
5010class Trim(Func):
5011    arg_types = {
5012        "this": True,
5013        "expression": False,
5014        "position": False,
5015        "collation": False,
5016    }
5017
5018
5019class TsOrDsAdd(Func, TimeUnit):
5020    arg_types = {"this": True, "expression": True, "unit": False}
5021
5022
5023class TsOrDsToDateStr(Func):
5024    pass
5025
5026
5027class TsOrDsToDate(Func):
5028    arg_types = {"this": True, "format": False}
5029
5030
5031class TsOrDiToDi(Func):
5032    pass
5033
5034
5035class Unhex(Func):
5036    pass
5037
5038
5039class UnixToStr(Func):
5040    arg_types = {"this": True, "format": False}
5041
5042
5043# https://prestodb.io/docs/current/functions/datetime.html
5044# presto has weird zone/hours/minutes
5045class UnixToTime(Func):
5046    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
5047
5048    SECONDS = Literal.string("seconds")
5049    MILLIS = Literal.string("millis")
5050    MICROS = Literal.string("micros")
5051
5052
5053class UnixToTimeStr(Func):
5054    pass
5055
5056
5057class Upper(Func):
5058    _sql_names = ["UPPER", "UCASE"]
5059
5060
5061class Variance(AggFunc):
5062    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
5063
5064
5065class VariancePop(AggFunc):
5066    _sql_names = ["VARIANCE_POP", "VAR_POP"]
5067
5068
5069class Week(Func):
5070    arg_types = {"this": True, "mode": False}
5071
5072
5073class XMLTable(Func):
5074    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
5075
5076
5077class Year(Func):
5078    pass
5079
5080
5081class Use(Expression):
5082    arg_types = {"this": True, "kind": False}
5083
5084
5085class Merge(Expression):
5086    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
5087
5088
5089class When(Func):
5090    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
5091
5092
5093# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
5094# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
5095class NextValueFor(Func):
5096    arg_types = {"this": True, "order": False}
5097
5098
5099def _norm_arg(arg):
5100    return arg.lower() if type(arg) is str else arg
5101
5102
5103ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
5104
5105
5106# Helpers
5107@t.overload
5108def maybe_parse(
5109    sql_or_expression: ExpOrStr,
5110    *,
5111    into: t.Type[E],
5112    dialect: DialectType = None,
5113    prefix: t.Optional[str] = None,
5114    copy: bool = False,
5115    **opts,
5116) -> E:
5117    ...
5118
5119
5120@t.overload
5121def maybe_parse(
5122    sql_or_expression: str | E,
5123    *,
5124    into: t.Optional[IntoType] = None,
5125    dialect: DialectType = None,
5126    prefix: t.Optional[str] = None,
5127    copy: bool = False,
5128    **opts,
5129) -> E:
5130    ...
5131
5132
5133def maybe_parse(
5134    sql_or_expression: ExpOrStr,
5135    *,
5136    into: t.Optional[IntoType] = None,
5137    dialect: DialectType = None,
5138    prefix: t.Optional[str] = None,
5139    copy: bool = False,
5140    **opts,
5141) -> Expression:
5142    """Gracefully handle a possible string or expression.
5143
5144    Example:
5145        >>> maybe_parse("1")
5146        (LITERAL this: 1, is_string: False)
5147        >>> maybe_parse(to_identifier("x"))
5148        (IDENTIFIER this: x, quoted: False)
5149
5150    Args:
5151        sql_or_expression: the SQL code string or an expression
5152        into: the SQLGlot Expression to parse into
5153        dialect: the dialect used to parse the input expressions (in the case that an
5154            input expression is a SQL string).
5155        prefix: a string to prefix the sql with before it gets parsed
5156            (automatically includes a space)
5157        copy: whether or not to copy the expression.
5158        **opts: other options to use to parse the input expressions (again, in the case
5159            that an input expression is a SQL string).
5160
5161    Returns:
5162        Expression: the parsed or given expression.
5163    """
5164    if isinstance(sql_or_expression, Expression):
5165        if copy:
5166            return sql_or_expression.copy()
5167        return sql_or_expression
5168
5169    if sql_or_expression is None:
5170        raise ParseError(f"SQL cannot be None")
5171
5172    import sqlglot
5173
5174    sql = str(sql_or_expression)
5175    if prefix:
5176        sql = f"{prefix} {sql}"
5177
5178    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
5179
5180
5181@t.overload
5182def maybe_copy(instance: None, copy: bool = True) -> None:
5183    ...
5184
5185
5186@t.overload
5187def maybe_copy(instance: E, copy: bool = True) -> E:
5188    ...
5189
5190
5191def maybe_copy(instance, copy=True):
5192    return instance.copy() if copy and instance else instance
5193
5194
5195def _is_wrong_expression(expression, into):
5196    return isinstance(expression, Expression) and not isinstance(expression, into)
5197
5198
5199def _apply_builder(
5200    expression,
5201    instance,
5202    arg,
5203    copy=True,
5204    prefix=None,
5205    into=None,
5206    dialect=None,
5207    into_arg="this",
5208    **opts,
5209):
5210    if _is_wrong_expression(expression, into):
5211        expression = into(**{into_arg: expression})
5212    instance = maybe_copy(instance, copy)
5213    expression = maybe_parse(
5214        sql_or_expression=expression,
5215        prefix=prefix,
5216        into=into,
5217        dialect=dialect,
5218        **opts,
5219    )
5220    instance.set(arg, expression)
5221    return instance
5222
5223
5224def _apply_child_list_builder(
5225    *expressions,
5226    instance,
5227    arg,
5228    append=True,
5229    copy=True,
5230    prefix=None,
5231    into=None,
5232    dialect=None,
5233    properties=None,
5234    **opts,
5235):
5236    instance = maybe_copy(instance, copy)
5237    parsed = []
5238    for expression in expressions:
5239        if expression is not None:
5240            if _is_wrong_expression(expression, into):
5241                expression = into(expressions=[expression])
5242
5243            expression = maybe_parse(
5244                expression,
5245                into=into,
5246                dialect=dialect,
5247                prefix=prefix,
5248                **opts,
5249            )
5250            parsed.extend(expression.expressions)
5251
5252    existing = instance.args.get(arg)
5253    if append and existing:
5254        parsed = existing.expressions + parsed
5255
5256    child = into(expressions=parsed)
5257    for k, v in (properties or {}).items():
5258        child.set(k, v)
5259    instance.set(arg, child)
5260
5261    return instance
5262
5263
5264def _apply_list_builder(
5265    *expressions,
5266    instance,
5267    arg,
5268    append=True,
5269    copy=True,
5270    prefix=None,
5271    into=None,
5272    dialect=None,
5273    **opts,
5274):
5275    inst = maybe_copy(instance, copy)
5276
5277    expressions = [
5278        maybe_parse(
5279            sql_or_expression=expression,
5280            into=into,
5281            prefix=prefix,
5282            dialect=dialect,
5283            **opts,
5284        )
5285        for expression in expressions
5286        if expression is not None
5287    ]
5288
5289    existing_expressions = inst.args.get(arg)
5290    if append and existing_expressions:
5291        expressions = existing_expressions + expressions
5292
5293    inst.set(arg, expressions)
5294    return inst
5295
5296
5297def _apply_conjunction_builder(
5298    *expressions,
5299    instance,
5300    arg,
5301    into=None,
5302    append=True,
5303    copy=True,
5304    dialect=None,
5305    **opts,
5306):
5307    expressions = [exp for exp in expressions if exp is not None and exp != ""]
5308    if not expressions:
5309        return instance
5310
5311    inst = maybe_copy(instance, copy)
5312
5313    existing = inst.args.get(arg)
5314    if append and existing is not None:
5315        expressions = [existing.this if into else existing] + list(expressions)
5316
5317    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
5318
5319    inst.set(arg, into(this=node) if into else node)
5320    return inst
5321
5322
5323def _apply_cte_builder(
5324    instance: E,
5325    alias: ExpOrStr,
5326    as_: ExpOrStr,
5327    recursive: t.Optional[bool] = None,
5328    append: bool = True,
5329    dialect: DialectType = None,
5330    copy: bool = True,
5331    **opts,
5332) -> E:
5333    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
5334    as_expression = maybe_parse(as_, dialect=dialect, **opts)
5335    cte = CTE(this=as_expression, alias=alias_expression)
5336    return _apply_child_list_builder(
5337        cte,
5338        instance=instance,
5339        arg="with",
5340        append=append,
5341        copy=copy,
5342        into=With,
5343        properties={"recursive": recursive or False},
5344    )
5345
5346
5347def _combine(
5348    expressions: t.Sequence[t.Optional[ExpOrStr]],
5349    operator: t.Type[Connector],
5350    dialect: DialectType = None,
5351    copy: bool = True,
5352    **opts,
5353) -> Expression:
5354    conditions = [
5355        condition(expression, dialect=dialect, copy=copy, **opts)
5356        for expression in expressions
5357        if expression is not None
5358    ]
5359
5360    this, *rest = conditions
5361    if rest:
5362        this = _wrap(this, Connector)
5363    for expression in rest:
5364        this = operator(this=this, expression=_wrap(expression, Connector))
5365
5366    return this
5367
5368
5369def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
5370    return Paren(this=expression) if isinstance(expression, kind) else expression
5371
5372
5373def union(
5374    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5375) -> Union:
5376    """
5377    Initializes a syntax tree from one UNION expression.
5378
5379    Example:
5380        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5381        'SELECT * FROM foo UNION SELECT * FROM bla'
5382
5383    Args:
5384        left: the SQL code string corresponding to the left-hand side.
5385            If an `Expression` instance is passed, it will be used as-is.
5386        right: the SQL code string corresponding to the right-hand side.
5387            If an `Expression` instance is passed, it will be used as-is.
5388        distinct: set the DISTINCT flag if and only if this is true.
5389        dialect: the dialect used to parse the input expression.
5390        opts: other options to use to parse the input expressions.
5391
5392    Returns:
5393        The new Union instance.
5394    """
5395    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5396    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5397
5398    return Union(this=left, expression=right, distinct=distinct)
5399
5400
5401def intersect(
5402    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5403) -> Intersect:
5404    """
5405    Initializes a syntax tree from one INTERSECT expression.
5406
5407    Example:
5408        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5409        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5410
5411    Args:
5412        left: the SQL code string corresponding to the left-hand side.
5413            If an `Expression` instance is passed, it will be used as-is.
5414        right: the SQL code string corresponding to the right-hand side.
5415            If an `Expression` instance is passed, it will be used as-is.
5416        distinct: set the DISTINCT flag if and only if this is true.
5417        dialect: the dialect used to parse the input expression.
5418        opts: other options to use to parse the input expressions.
5419
5420    Returns:
5421        The new Intersect instance.
5422    """
5423    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5424    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5425
5426    return Intersect(this=left, expression=right, distinct=distinct)
5427
5428
5429def except_(
5430    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5431) -> Except:
5432    """
5433    Initializes a syntax tree from one EXCEPT expression.
5434
5435    Example:
5436        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5437        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5438
5439    Args:
5440        left: the SQL code string corresponding to the left-hand side.
5441            If an `Expression` instance is passed, it will be used as-is.
5442        right: the SQL code string corresponding to the right-hand side.
5443            If an `Expression` instance is passed, it will be used as-is.
5444        distinct: set the DISTINCT flag if and only if this is true.
5445        dialect: the dialect used to parse the input expression.
5446        opts: other options to use to parse the input expressions.
5447
5448    Returns:
5449        The new Except instance.
5450    """
5451    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5452    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5453
5454    return Except(this=left, expression=right, distinct=distinct)
5455
5456
5457def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5458    """
5459    Initializes a syntax tree from one or multiple SELECT expressions.
5460
5461    Example:
5462        >>> select("col1", "col2").from_("tbl").sql()
5463        'SELECT col1, col2 FROM tbl'
5464
5465    Args:
5466        *expressions: the SQL code string to parse as the expressions of a
5467            SELECT statement. If an Expression instance is passed, this is used as-is.
5468        dialect: the dialect used to parse the input expressions (in the case that an
5469            input expression is a SQL string).
5470        **opts: other options to use to parse the input expressions (again, in the case
5471            that an input expression is a SQL string).
5472
5473    Returns:
5474        Select: the syntax tree for the SELECT statement.
5475    """
5476    return Select().select(*expressions, dialect=dialect, **opts)
5477
5478
5479def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5480    """
5481    Initializes a syntax tree from a FROM expression.
5482
5483    Example:
5484        >>> from_("tbl").select("col1", "col2").sql()
5485        'SELECT col1, col2 FROM tbl'
5486
5487    Args:
5488        *expression: the SQL code string to parse as the FROM expressions of a
5489            SELECT statement. If an Expression instance is passed, this is used as-is.
5490        dialect: the dialect used to parse the input expression (in the case that the
5491            input expression is a SQL string).
5492        **opts: other options to use to parse the input expressions (again, in the case
5493            that the input expression is a SQL string).
5494
5495    Returns:
5496        Select: the syntax tree for the SELECT statement.
5497    """
5498    return Select().from_(expression, dialect=dialect, **opts)
5499
5500
5501def update(
5502    table: str | Table,
5503    properties: dict,
5504    where: t.Optional[ExpOrStr] = None,
5505    from_: t.Optional[ExpOrStr] = None,
5506    dialect: DialectType = None,
5507    **opts,
5508) -> Update:
5509    """
5510    Creates an update statement.
5511
5512    Example:
5513        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5514        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5515
5516    Args:
5517        *properties: dictionary of properties to set which are
5518            auto converted to sql objects eg None -> NULL
5519        where: sql conditional parsed into a WHERE statement
5520        from_: sql statement parsed into a FROM statement
5521        dialect: the dialect used to parse the input expressions.
5522        **opts: other options to use to parse the input expressions.
5523
5524    Returns:
5525        Update: the syntax tree for the UPDATE statement.
5526    """
5527    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5528    update_expr.set(
5529        "expressions",
5530        [
5531            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5532            for k, v in properties.items()
5533        ],
5534    )
5535    if from_:
5536        update_expr.set(
5537            "from",
5538            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5539        )
5540    if isinstance(where, Condition):
5541        where = Where(this=where)
5542    if where:
5543        update_expr.set(
5544            "where",
5545            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5546        )
5547    return update_expr
5548
5549
5550def delete(
5551    table: ExpOrStr,
5552    where: t.Optional[ExpOrStr] = None,
5553    returning: t.Optional[ExpOrStr] = None,
5554    dialect: DialectType = None,
5555    **opts,
5556) -> Delete:
5557    """
5558    Builds a delete statement.
5559
5560    Example:
5561        >>> delete("my_table", where="id > 1").sql()
5562        'DELETE FROM my_table WHERE id > 1'
5563
5564    Args:
5565        where: sql conditional parsed into a WHERE statement
5566        returning: sql conditional parsed into a RETURNING statement
5567        dialect: the dialect used to parse the input expressions.
5568        **opts: other options to use to parse the input expressions.
5569
5570    Returns:
5571        Delete: the syntax tree for the DELETE statement.
5572    """
5573    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5574    if where:
5575        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5576    if returning:
5577        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5578    return delete_expr
5579
5580
5581def insert(
5582    expression: ExpOrStr,
5583    into: ExpOrStr,
5584    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5585    overwrite: t.Optional[bool] = None,
5586    dialect: DialectType = None,
5587    copy: bool = True,
5588    **opts,
5589) -> Insert:
5590    """
5591    Builds an INSERT statement.
5592
5593    Example:
5594        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5595        'INSERT INTO tbl VALUES (1, 2, 3)'
5596
5597    Args:
5598        expression: the sql string or expression of the INSERT statement
5599        into: the tbl to insert data to.
5600        columns: optionally the table's column names.
5601        overwrite: whether to INSERT OVERWRITE or not.
5602        dialect: the dialect used to parse the input expressions.
5603        copy: whether or not to copy the expression.
5604        **opts: other options to use to parse the input expressions.
5605
5606    Returns:
5607        Insert: the syntax tree for the INSERT statement.
5608    """
5609    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5610    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5611
5612    if columns:
5613        this = _apply_list_builder(
5614            *columns,
5615            instance=Schema(this=this),
5616            arg="expressions",
5617            into=Identifier,
5618            copy=False,
5619            dialect=dialect,
5620            **opts,
5621        )
5622
5623    return Insert(this=this, expression=expr, overwrite=overwrite)
5624
5625
5626def condition(
5627    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5628) -> Condition:
5629    """
5630    Initialize a logical condition expression.
5631
5632    Example:
5633        >>> condition("x=1").sql()
5634        'x = 1'
5635
5636        This is helpful for composing larger logical syntax trees:
5637        >>> where = condition("x=1")
5638        >>> where = where.and_("y=1")
5639        >>> Select().from_("tbl").select("*").where(where).sql()
5640        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5641
5642    Args:
5643        *expression: the SQL code string to parse.
5644            If an Expression instance is passed, this is used as-is.
5645        dialect: the dialect used to parse the input expression (in the case that the
5646            input expression is a SQL string).
5647        copy: Whether or not to copy `expression` (only applies to expressions).
5648        **opts: other options to use to parse the input expressions (again, in the case
5649            that the input expression is a SQL string).
5650
5651    Returns:
5652        The new Condition instance
5653    """
5654    return maybe_parse(
5655        expression,
5656        into=Condition,
5657        dialect=dialect,
5658        copy=copy,
5659        **opts,
5660    )
5661
5662
5663def and_(
5664    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5665) -> Condition:
5666    """
5667    Combine multiple conditions with an AND logical operator.
5668
5669    Example:
5670        >>> and_("x=1", and_("y=1", "z=1")).sql()
5671        'x = 1 AND (y = 1 AND z = 1)'
5672
5673    Args:
5674        *expressions: the SQL code strings to parse.
5675            If an Expression instance is passed, this is used as-is.
5676        dialect: the dialect used to parse the input expression.
5677        copy: whether or not to copy `expressions` (only applies to Expressions).
5678        **opts: other options to use to parse the input expressions.
5679
5680    Returns:
5681        And: the new condition
5682    """
5683    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
5684
5685
5686def or_(
5687    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5688) -> Condition:
5689    """
5690    Combine multiple conditions with an OR logical operator.
5691
5692    Example:
5693        >>> or_("x=1", or_("y=1", "z=1")).sql()
5694        'x = 1 OR (y = 1 OR z = 1)'
5695
5696    Args:
5697        *expressions: the SQL code strings to parse.
5698            If an Expression instance is passed, this is used as-is.
5699        dialect: the dialect used to parse the input expression.
5700        copy: whether or not to copy `expressions` (only applies to Expressions).
5701        **opts: other options to use to parse the input expressions.
5702
5703    Returns:
5704        Or: the new condition
5705    """
5706    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
5707
5708
5709def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5710    """
5711    Wrap a condition with a NOT operator.
5712
5713    Example:
5714        >>> not_("this_suit='black'").sql()
5715        "NOT this_suit = 'black'"
5716
5717    Args:
5718        expression: the SQL code string to parse.
5719            If an Expression instance is passed, this is used as-is.
5720        dialect: the dialect used to parse the input expression.
5721        copy: whether to copy the expression or not.
5722        **opts: other options to use to parse the input expressions.
5723
5724    Returns:
5725        The new condition.
5726    """
5727    this = condition(
5728        expression,
5729        dialect=dialect,
5730        copy=copy,
5731        **opts,
5732    )
5733    return Not(this=_wrap(this, Connector))
5734
5735
5736def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5737    """
5738    Wrap an expression in parentheses.
5739
5740    Example:
5741        >>> paren("5 + 3").sql()
5742        '(5 + 3)'
5743
5744    Args:
5745        expression: the SQL code string to parse.
5746            If an Expression instance is passed, this is used as-is.
5747        copy: whether to copy the expression or not.
5748
5749    Returns:
5750        The wrapped expression.
5751    """
5752    return Paren(this=maybe_parse(expression, copy=copy))
5753
5754
5755SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
5756
5757
5758@t.overload
5759def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
5760    ...
5761
5762
5763@t.overload
5764def to_identifier(
5765    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
5766) -> Identifier:
5767    ...
5768
5769
5770def to_identifier(name, quoted=None, copy=True):
5771    """Builds an identifier.
5772
5773    Args:
5774        name: The name to turn into an identifier.
5775        quoted: Whether or not force quote the identifier.
5776        copy: Whether or not to copy a passed in Identefier node.
5777
5778    Returns:
5779        The identifier ast node.
5780    """
5781
5782    if name is None:
5783        return None
5784
5785    if isinstance(name, Identifier):
5786        identifier = maybe_copy(name, copy)
5787    elif isinstance(name, str):
5788        identifier = Identifier(
5789            this=name,
5790            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5791        )
5792    else:
5793        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5794    return identifier
5795
5796
5797INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
5798
5799
5800def to_interval(interval: str | Literal) -> Interval:
5801    """Builds an interval expression from a string like '1 day' or '5 months'."""
5802    if isinstance(interval, Literal):
5803        if not interval.is_string:
5804            raise ValueError("Invalid interval string.")
5805
5806        interval = interval.this
5807
5808    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5809
5810    if not interval_parts:
5811        raise ValueError("Invalid interval string.")
5812
5813    return Interval(
5814        this=Literal.string(interval_parts.group(1)),
5815        unit=Var(this=interval_parts.group(2)),
5816    )
5817
5818
5819@t.overload
5820def to_table(sql_path: str | Table, **kwargs) -> Table:
5821    ...
5822
5823
5824@t.overload
5825def to_table(sql_path: None, **kwargs) -> None:
5826    ...
5827
5828
5829def to_table(
5830    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5831) -> t.Optional[Table]:
5832    """
5833    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5834    If a table is passed in then that table is returned.
5835
5836    Args:
5837        sql_path: a `[catalog].[schema].[table]` string.
5838        dialect: the source dialect according to which the table name will be parsed.
5839        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5840
5841    Returns:
5842        A table expression.
5843    """
5844    if sql_path is None or isinstance(sql_path, Table):
5845        return sql_path
5846    if not isinstance(sql_path, str):
5847        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5848
5849    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5850    if table:
5851        for k, v in kwargs.items():
5852            table.set(k, v)
5853
5854    return table
5855
5856
5857def to_column(sql_path: str | Column, **kwargs) -> Column:
5858    """
5859    Create a column from a `[table].[column]` sql path. Schema is optional.
5860
5861    If a column is passed in then that column is returned.
5862
5863    Args:
5864        sql_path: `[table].[column]` string
5865    Returns:
5866        Table: A column expression
5867    """
5868    if sql_path is None or isinstance(sql_path, Column):
5869        return sql_path
5870    if not isinstance(sql_path, str):
5871        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5872    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
5873
5874
5875def alias_(
5876    expression: ExpOrStr,
5877    alias: str | Identifier,
5878    table: bool | t.Sequence[str | Identifier] = False,
5879    quoted: t.Optional[bool] = None,
5880    dialect: DialectType = None,
5881    copy: bool = True,
5882    **opts,
5883):
5884    """Create an Alias expression.
5885
5886    Example:
5887        >>> alias_('foo', 'bar').sql()
5888        'foo AS bar'
5889
5890        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5891        '(SELECT 1, 2) AS bar(a, b)'
5892
5893    Args:
5894        expression: the SQL code strings to parse.
5895            If an Expression instance is passed, this is used as-is.
5896        alias: the alias name to use. If the name has
5897            special characters it is quoted.
5898        table: Whether or not to create a table alias, can also be a list of columns.
5899        quoted: whether or not to quote the alias
5900        dialect: the dialect used to parse the input expression.
5901        copy: Whether or not to copy the expression.
5902        **opts: other options to use to parse the input expressions.
5903
5904    Returns:
5905        Alias: the aliased expression
5906    """
5907    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5908    alias = to_identifier(alias, quoted=quoted)
5909
5910    if table:
5911        table_alias = TableAlias(this=alias)
5912        exp.set("alias", table_alias)
5913
5914        if not isinstance(table, bool):
5915            for column in table:
5916                table_alias.append("columns", to_identifier(column, quoted=quoted))
5917
5918        return exp
5919
5920    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5921    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5922    # for the complete Window expression.
5923    #
5924    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5925
5926    if "alias" in exp.arg_types and not isinstance(exp, Window):
5927        exp.set("alias", alias)
5928        return exp
5929    return Alias(this=exp, alias=alias)
5930
5931
5932def subquery(
5933    expression: ExpOrStr,
5934    alias: t.Optional[Identifier | str] = None,
5935    dialect: DialectType = None,
5936    **opts,
5937) -> Select:
5938    """
5939    Build a subquery expression.
5940
5941    Example:
5942        >>> subquery('select x from tbl', 'bar').select('x').sql()
5943        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5944
5945    Args:
5946        expression: the SQL code strings to parse.
5947            If an Expression instance is passed, this is used as-is.
5948        alias: the alias name to use.
5949        dialect: the dialect used to parse the input expression.
5950        **opts: other options to use to parse the input expressions.
5951
5952    Returns:
5953        A new Select instance with the subquery expression included.
5954    """
5955
5956    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5957    return Select().from_(expression, dialect=dialect, **opts)
5958
5959
5960def column(
5961    col: str | Identifier,
5962    table: t.Optional[str | Identifier] = None,
5963    db: t.Optional[str | Identifier] = None,
5964    catalog: t.Optional[str | Identifier] = None,
5965    quoted: t.Optional[bool] = None,
5966) -> Column:
5967    """
5968    Build a Column.
5969
5970    Args:
5971        col: Column name.
5972        table: Table name.
5973        db: Database name.
5974        catalog: Catalog name.
5975        quoted: Whether to force quotes on the column's identifiers.
5976
5977    Returns:
5978        The new Column instance.
5979    """
5980    return Column(
5981        this=to_identifier(col, quoted=quoted),
5982        table=to_identifier(table, quoted=quoted),
5983        db=to_identifier(db, quoted=quoted),
5984        catalog=to_identifier(catalog, quoted=quoted),
5985    )
5986
5987
5988def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5989    """Cast an expression to a data type.
5990
5991    Example:
5992        >>> cast('x + 1', 'int').sql()
5993        'CAST(x + 1 AS INT)'
5994
5995    Args:
5996        expression: The expression to cast.
5997        to: The datatype to cast to.
5998
5999    Returns:
6000        The new Cast instance.
6001    """
6002    expression = maybe_parse(expression, **opts)
6003    data_type = DataType.build(to, **opts)
6004    expression = Cast(this=expression, to=data_type)
6005    expression.type = data_type
6006    return expression
6007
6008
6009def table_(
6010    table: Identifier | str,
6011    db: t.Optional[Identifier | str] = None,
6012    catalog: t.Optional[Identifier | str] = None,
6013    quoted: t.Optional[bool] = None,
6014    alias: t.Optional[Identifier | str] = None,
6015) -> Table:
6016    """Build a Table.
6017
6018    Args:
6019        table: Table name.
6020        db: Database name.
6021        catalog: Catalog name.
6022        quote: Whether to force quotes on the table's identifiers.
6023        alias: Table's alias.
6024
6025    Returns:
6026        The new Table instance.
6027    """
6028    return Table(
6029        this=to_identifier(table, quoted=quoted) if table else None,
6030        db=to_identifier(db, quoted=quoted) if db else None,
6031        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
6032        alias=TableAlias(this=to_identifier(alias)) if alias else None,
6033    )
6034
6035
6036def values(
6037    values: t.Iterable[t.Tuple[t.Any, ...]],
6038    alias: t.Optional[str] = None,
6039    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
6040) -> Values:
6041    """Build VALUES statement.
6042
6043    Example:
6044        >>> values([(1, '2')]).sql()
6045        "VALUES (1, '2')"
6046
6047    Args:
6048        values: values statements that will be converted to SQL
6049        alias: optional alias
6050        columns: Optional list of ordered column names or ordered dictionary of column names to types.
6051         If either are provided then an alias is also required.
6052
6053    Returns:
6054        Values: the Values expression object
6055    """
6056    if columns and not alias:
6057        raise ValueError("Alias is required when providing columns")
6058
6059    return Values(
6060        expressions=[convert(tup) for tup in values],
6061        alias=(
6062            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
6063            if columns
6064            else (TableAlias(this=to_identifier(alias)) if alias else None)
6065        ),
6066    )
6067
6068
6069def var(name: t.Optional[ExpOrStr]) -> Var:
6070    """Build a SQL variable.
6071
6072    Example:
6073        >>> repr(var('x'))
6074        '(VAR this: x)'
6075
6076        >>> repr(var(column('x', table='y')))
6077        '(VAR this: x)'
6078
6079    Args:
6080        name: The name of the var or an expression who's name will become the var.
6081
6082    Returns:
6083        The new variable node.
6084    """
6085    if not name:
6086        raise ValueError("Cannot convert empty name into var.")
6087
6088    if isinstance(name, Expression):
6089        name = name.name
6090    return Var(this=name)
6091
6092
6093def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
6094    """Build ALTER TABLE... RENAME... expression
6095
6096    Args:
6097        old_name: The old name of the table
6098        new_name: The new name of the table
6099
6100    Returns:
6101        Alter table expression
6102    """
6103    old_table = to_table(old_name)
6104    new_table = to_table(new_name)
6105    return AlterTable(
6106        this=old_table,
6107        actions=[
6108            RenameTable(this=new_table),
6109        ],
6110    )
6111
6112
6113def convert(value: t.Any, copy: bool = False) -> Expression:
6114    """Convert a python value into an expression object.
6115
6116    Raises an error if a conversion is not possible.
6117
6118    Args:
6119        value: A python object.
6120        copy: Whether or not to copy `value` (only applies to Expressions and collections).
6121
6122    Returns:
6123        Expression: the equivalent expression object.
6124    """
6125    if isinstance(value, Expression):
6126        return maybe_copy(value, copy)
6127    if isinstance(value, str):
6128        return Literal.string(value)
6129    if isinstance(value, bool):
6130        return Boolean(this=value)
6131    if value is None or (isinstance(value, float) and math.isnan(value)):
6132        return NULL
6133    if isinstance(value, numbers.Number):
6134        return Literal.number(value)
6135    if isinstance(value, datetime.datetime):
6136        datetime_literal = Literal.string(
6137            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
6138        )
6139        return TimeStrToTime(this=datetime_literal)
6140    if isinstance(value, datetime.date):
6141        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6142        return DateStrToDate(this=date_literal)
6143    if isinstance(value, tuple):
6144        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6145    if isinstance(value, list):
6146        return Array(expressions=[convert(v, copy=copy) for v in value])
6147    if isinstance(value, dict):
6148        return Map(
6149            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6150            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6151        )
6152    raise ValueError(f"Cannot convert {value}")
6153
6154
6155def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6156    """
6157    Replace children of an expression with the result of a lambda fun(child) -> exp.
6158    """
6159    for k, v in expression.args.items():
6160        is_list_arg = type(v) is list
6161
6162        child_nodes = v if is_list_arg else [v]
6163        new_child_nodes = []
6164
6165        for cn in child_nodes:
6166            if isinstance(cn, Expression):
6167                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6168                    new_child_nodes.append(child_node)
6169                    child_node.parent = expression
6170                    child_node.arg_key = k
6171            else:
6172                new_child_nodes.append(cn)
6173
6174        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
6175
6176
6177def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6178    """
6179    Return all table names referenced through columns in an expression.
6180
6181    Example:
6182        >>> import sqlglot
6183        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6184        ['a', 'c']
6185
6186    Args:
6187        expression: expression to find table names.
6188        exclude: a table name to exclude
6189
6190    Returns:
6191        A list of unique names.
6192    """
6193    return {
6194        table
6195        for table in (column.table for column in expression.find_all(Column))
6196        if table and table != exclude
6197    }
6198
6199
6200def table_name(table: Table | str, dialect: DialectType = None) -> str:
6201    """Get the full name of a table as a string.
6202
6203    Args:
6204        table: Table expression node or string.
6205        dialect: The dialect to generate the table name for.
6206
6207    Examples:
6208        >>> from sqlglot import exp, parse_one
6209        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6210        'a.b.c'
6211
6212    Returns:
6213        The table name.
6214    """
6215
6216    table = maybe_parse(table, into=Table, dialect=dialect)
6217
6218    if not table:
6219        raise ValueError(f"Cannot parse {table}")
6220
6221    return ".".join(
6222        part.sql(dialect=dialect, identify=True)
6223        if not SAFE_IDENTIFIER_RE.match(part.name)
6224        else part.name
6225        for part in table.parts
6226    )
6227
6228
6229def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6230    """Replace all tables in expression according to the mapping.
6231
6232    Args:
6233        expression: expression node to be transformed and replaced.
6234        mapping: mapping of table names.
6235        copy: whether or not to copy the expression.
6236
6237    Examples:
6238        >>> from sqlglot import exp, parse_one
6239        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6240        'SELECT * FROM c'
6241
6242    Returns:
6243        The mapped expression.
6244    """
6245
6246    def _replace_tables(node: Expression) -> Expression:
6247        if isinstance(node, Table):
6248            new_name = mapping.get(table_name(node))
6249            if new_name:
6250                return to_table(
6251                    new_name,
6252                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6253                )
6254        return node
6255
6256    return expression.transform(_replace_tables, copy=copy)
6257
6258
6259def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6260    """Replace placeholders in an expression.
6261
6262    Args:
6263        expression: expression node to be transformed and replaced.
6264        args: positional names that will substitute unnamed placeholders in the given order.
6265        kwargs: keyword arguments that will substitute named placeholders.
6266
6267    Examples:
6268        >>> from sqlglot import exp, parse_one
6269        >>> replace_placeholders(
6270        ...     parse_one("select * from :tbl where ? = ?"),
6271        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6272        ... ).sql()
6273        "SELECT * FROM foo WHERE str_col = 'b'"
6274
6275    Returns:
6276        The mapped expression.
6277    """
6278
6279    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6280        if isinstance(node, Placeholder):
6281            if node.name:
6282                new_name = kwargs.get(node.name)
6283                if new_name:
6284                    return convert(new_name)
6285            else:
6286                try:
6287                    return convert(next(args))
6288                except StopIteration:
6289                    pass
6290        return node
6291
6292    return expression.transform(_replace_placeholders, iter(args), **kwargs)
6293
6294
6295def expand(
6296    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6297) -> Expression:
6298    """Transforms an expression by expanding all referenced sources into subqueries.
6299
6300    Examples:
6301        >>> from sqlglot import parse_one
6302        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6303        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6304
6305        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6306        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6307
6308    Args:
6309        expression: The expression to expand.
6310        sources: A dictionary of name to Subqueryables.
6311        copy: Whether or not to copy the expression during transformation. Defaults to True.
6312
6313    Returns:
6314        The transformed expression.
6315    """
6316
6317    def _expand(node: Expression):
6318        if isinstance(node, Table):
6319            name = table_name(node)
6320            source = sources.get(name)
6321            if source:
6322                subquery = source.subquery(node.alias or name)
6323                subquery.comments = [f"source: {name}"]
6324                return subquery.transform(_expand, copy=False)
6325        return node
6326
6327    return expression.transform(_expand, copy=copy)
6328
6329
6330def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6331    """
6332    Returns a Func expression.
6333
6334    Examples:
6335        >>> func("abs", 5).sql()
6336        'ABS(5)'
6337
6338        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6339        'CAST(5 AS DOUBLE)'
6340
6341    Args:
6342        name: the name of the function to build.
6343        args: the args used to instantiate the function of interest.
6344        dialect: the source dialect.
6345        kwargs: the kwargs used to instantiate the function of interest.
6346
6347    Note:
6348        The arguments `args` and `kwargs` are mutually exclusive.
6349
6350    Returns:
6351        An instance of the function of interest, or an anonymous function, if `name` doesn't
6352        correspond to an existing `sqlglot.expressions.Func` class.
6353    """
6354    if args and kwargs:
6355        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6356
6357    from sqlglot.dialects.dialect import Dialect
6358
6359    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6360    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6361
6362    parser = Dialect.get_or_raise(dialect)().parser()
6363    from_args_list = parser.FUNCTIONS.get(name.upper())
6364
6365    if from_args_list:
6366        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6367    else:
6368        kwargs = kwargs or {"expressions": converted}
6369        function = Anonymous(this=name, **kwargs)
6370
6371    for error_message in function.error_messages(converted):
6372        raise ValueError(error_message)
6373
6374    return function
6375
6376
6377def true() -> Boolean:
6378    """
6379    Returns a true Boolean expression.
6380    """
6381    return Boolean(this=True)
6382
6383
6384def false() -> Boolean:
6385    """
6386    Returns a false Boolean expression.
6387    """
6388    return Boolean(this=False)
6389
6390
6391def null() -> Null:
6392    """
6393    Returns a Null expression.
6394    """
6395    return Null()
6396
6397
6398# TODO: deprecate this
6399TRUE = Boolean(this=True)
6400FALSE = Boolean(this=False)
6401NULL = Null()
SQLGLOT_META = 'sqlglot.meta'
class Expression:
 59class Expression(metaclass=_Expression):
 60    """
 61    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 62    context, such as its child expressions, their names (arg keys), and whether a given child expression
 63    is optional or not.
 64
 65    Attributes:
 66        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 67            and representing expressions as strings.
 68        arg_types: determines what arguments (child nodes) are supported by an expression. It
 69            maps arg keys to booleans that indicate whether the corresponding args are optional.
 70        parent: a reference to the parent expression (or None, in case of root expressions).
 71        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 72            uses to refer to it.
 73        comments: a list of comments that are associated with a given expression. This is used in
 74            order to preserve comments when transpiling SQL code.
 75        type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 76            optimizer, in order to enable some transformations that require type information.
 77        meta: a dictionary that can be used to store useful metadata for a given expression.
 78
 79    Example:
 80        >>> class Foo(Expression):
 81        ...     arg_types = {"this": True, "expression": False}
 82
 83        The above definition informs us that Foo is an Expression that requires an argument called
 84        "this" and may also optionally receive an argument called "expression".
 85
 86    Args:
 87        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 88    """
 89
 90    key = "expression"
 91    arg_types = {"this": True}
 92    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 93
 94    def __init__(self, **args: t.Any):
 95        self.args: t.Dict[str, t.Any] = args
 96        self.parent: t.Optional[Expression] = None
 97        self.arg_key: t.Optional[str] = None
 98        self.comments: t.Optional[t.List[str]] = None
 99        self._type: t.Optional[DataType] = None
100        self._meta: t.Optional[t.Dict[str, t.Any]] = None
101        self._hash: t.Optional[int] = None
102
103        for arg_key, value in self.args.items():
104            self._set_parent(arg_key, value)
105
106    def __eq__(self, other) -> bool:
107        return type(self) is type(other) and hash(self) == hash(other)
108
109    @property
110    def hashable_args(self) -> t.Any:
111        return frozenset(
112            (k, tuple(_norm_arg(a) for a in v) if type(v) is list else _norm_arg(v))
113            for k, v in self.args.items()
114            if not (v is None or v is False or (type(v) is list and not v))
115        )
116
117    def __hash__(self) -> int:
118        if self._hash is not None:
119            return self._hash
120
121        return hash((self.__class__, self.hashable_args))
122
123    @property
124    def this(self):
125        """
126        Retrieves the argument with key "this".
127        """
128        return self.args.get("this")
129
130    @property
131    def expression(self):
132        """
133        Retrieves the argument with key "expression".
134        """
135        return self.args.get("expression")
136
137    @property
138    def expressions(self):
139        """
140        Retrieves the argument with key "expressions".
141        """
142        return self.args.get("expressions") or []
143
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""
157
158    @property
159    def is_string(self) -> bool:
160        """
161        Checks whether a Literal expression is a string.
162        """
163        return isinstance(self, Literal) and self.args["is_string"]
164
165    @property
166    def is_number(self) -> bool:
167        """
168        Checks whether a Literal expression is a number.
169        """
170        return isinstance(self, Literal) and not self.args["is_string"]
171
172    @property
173    def is_int(self) -> bool:
174        """
175        Checks whether a Literal expression is an integer.
176        """
177        if self.is_number:
178            try:
179                int(self.name)
180                return True
181            except ValueError:
182                pass
183        return False
184
185    @property
186    def is_star(self) -> bool:
187        """Checks whether an expression is a star."""
188        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
189
190    @property
191    def alias(self) -> str:
192        """
193        Returns the alias of the expression, or an empty string if it's not aliased.
194        """
195        if isinstance(self.args.get("alias"), TableAlias):
196            return self.args["alias"].name
197        return self.text("alias")
198
199    @property
200    def alias_column_names(self) -> t.List[str]:
201        table_alias = self.args.get("alias")
202        if not table_alias:
203            return []
204        return [c.name for c in table_alias.args.get("columns") or []]
205
206    @property
207    def name(self) -> str:
208        return self.text("this")
209
210    @property
211    def alias_or_name(self) -> str:
212        return self.alias or self.name
213
214    @property
215    def output_name(self) -> str:
216        """
217        Name of the output column if this expression is a selection.
218
219        If the Expression has no output name, an empty string is returned.
220
221        Example:
222            >>> from sqlglot import parse_one
223            >>> parse_one("SELECT a").expressions[0].output_name
224            'a'
225            >>> parse_one("SELECT b AS c").expressions[0].output_name
226            'c'
227            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
228            ''
229        """
230        return ""
231
232    @property
233    def type(self) -> t.Optional[DataType]:
234        return self._type
235
236    @type.setter
237    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
238        if dtype and not isinstance(dtype, DataType):
239            dtype = DataType.build(dtype)
240        self._type = dtype  # type: ignore
241
242    @property
243    def meta(self) -> t.Dict[str, t.Any]:
244        if self._meta is None:
245            self._meta = {}
246        return self._meta
247
248    def __deepcopy__(self, memo):
249        copy = self.__class__(**deepcopy(self.args))
250        if self.comments is not None:
251            copy.comments = deepcopy(self.comments)
252
253        if self._type is not None:
254            copy._type = self._type.copy()
255
256        if self._meta is not None:
257            copy._meta = deepcopy(self._meta)
258
259        return copy
260
261    def copy(self):
262        """
263        Returns a deep copy of the expression.
264        """
265        new = deepcopy(self)
266        new.parent = self.parent
267        return new
268
269    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
270        if self.comments is None:
271            self.comments = []
272        if comments:
273            for comment in comments:
274                _, *meta = comment.split(SQLGLOT_META)
275                if meta:
276                    for kv in "".join(meta).split(","):
277                        k, *v = kv.split("=")
278                        value = v[0].strip() if v else True
279                        self.meta[k.strip()] = value
280                self.comments.append(comment)
281
282    def append(self, arg_key: str, value: t.Any) -> None:
283        """
284        Appends value to arg_key if it's a list or sets it as a new list.
285
286        Args:
287            arg_key (str): name of the list expression arg
288            value (Any): value to append to the list
289        """
290        if not isinstance(self.args.get(arg_key), list):
291            self.args[arg_key] = []
292        self.args[arg_key].append(value)
293        self._set_parent(arg_key, value)
294
295    def set(self, arg_key: str, value: t.Any) -> None:
296        """
297        Sets arg_key to value.
298
299        Args:
300            arg_key: name of the expression arg.
301            value: value to set the arg to.
302        """
303        if value is None:
304            self.args.pop(arg_key, None)
305            return
306
307        self.args[arg_key] = value
308        self._set_parent(arg_key, value)
309
310    def _set_parent(self, arg_key: str, value: t.Any) -> None:
311        if hasattr(value, "parent"):
312            value.parent = self
313            value.arg_key = arg_key
314        elif type(value) is list:
315            for v in value:
316                if hasattr(v, "parent"):
317                    v.parent = self
318                    v.arg_key = arg_key
319
320    @property
321    def depth(self) -> int:
322        """
323        Returns the depth of this tree.
324        """
325        if self.parent:
326            return self.parent.depth + 1
327        return 0
328
329    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
330        """Yields the key and expression for all arguments, exploding list args."""
331        for k, vs in self.args.items():
332            if type(vs) is list:
333                for v in vs:
334                    if hasattr(v, "parent"):
335                        yield k, v
336            else:
337                if hasattr(vs, "parent"):
338                    yield k, vs
339
340    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
341        """
342        Returns the first node in this tree which matches at least one of
343        the specified types.
344
345        Args:
346            expression_types: the expression type(s) to match.
347            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
348
349        Returns:
350            The node which matches the criteria or None if no such node was found.
351        """
352        return next(self.find_all(*expression_types, bfs=bfs), None)
353
354    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
355        """
356        Returns a generator object which visits all nodes in this tree and only
357        yields those that match at least one of the specified expression types.
358
359        Args:
360            expression_types: the expression type(s) to match.
361            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
362
363        Returns:
364            The generator object.
365        """
366        for expression, *_ in self.walk(bfs=bfs):
367            if isinstance(expression, expression_types):
368                yield expression
369
370    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
371        """
372        Returns a nearest parent matching expression_types.
373
374        Args:
375            expression_types: the expression type(s) to match.
376
377        Returns:
378            The parent node.
379        """
380        ancestor = self.parent
381        while ancestor and not isinstance(ancestor, expression_types):
382            ancestor = ancestor.parent
383        return t.cast(E, ancestor)
384
385    @property
386    def parent_select(self) -> t.Optional[Select]:
387        """
388        Returns the parent select statement.
389        """
390        return self.find_ancestor(Select)
391
392    @property
393    def same_parent(self) -> bool:
394        """Returns if the parent is the same class as itself."""
395        return type(self.parent) is self.__class__
396
397    def root(self) -> Expression:
398        """
399        Returns the root expression of this tree.
400        """
401        expression = self
402        while expression.parent:
403            expression = expression.parent
404        return expression
405
406    def walk(self, bfs=True, prune=None):
407        """
408        Returns a generator object which visits all nodes in this tree.
409
410        Args:
411            bfs (bool): if set to True the BFS traversal order will be applied,
412                otherwise the DFS traversal will be used instead.
413            prune ((node, parent, arg_key) -> bool): callable that returns True if
414                the generator should stop traversing this branch of the tree.
415
416        Returns:
417            the generator object.
418        """
419        if bfs:
420            yield from self.bfs(prune=prune)
421        else:
422            yield from self.dfs(prune=prune)
423
424    def dfs(self, parent=None, key=None, prune=None):
425        """
426        Returns a generator object which visits all nodes in this tree in
427        the DFS (Depth-first) order.
428
429        Returns:
430            The generator object.
431        """
432        parent = parent or self.parent
433        yield self, parent, key
434        if prune and prune(self, parent, key):
435            return
436
437        for k, v in self.iter_expressions():
438            yield from v.dfs(self, k, prune)
439
440    def bfs(self, prune=None):
441        """
442        Returns a generator object which visits all nodes in this tree in
443        the BFS (Breadth-first) order.
444
445        Returns:
446            The generator object.
447        """
448        queue = deque([(self, self.parent, None)])
449
450        while queue:
451            item, parent, key = queue.popleft()
452
453            yield item, parent, key
454            if prune and prune(item, parent, key):
455                continue
456
457            for k, v in item.iter_expressions():
458                queue.append((v, item, k))
459
460    def unnest(self):
461        """
462        Returns the first non parenthesis child or self.
463        """
464        expression = self
465        while type(expression) is Paren:
466            expression = expression.this
467        return expression
468
469    def unalias(self):
470        """
471        Returns the inner expression if this is an Alias.
472        """
473        if isinstance(self, Alias):
474            return self.this
475        return self
476
477    def unnest_operands(self):
478        """
479        Returns unnested operands as a tuple.
480        """
481        return tuple(arg.unnest() for _, arg in self.iter_expressions())
482
483    def flatten(self, unnest=True):
484        """
485        Returns a generator which yields child nodes who's parents are the same class.
486
487        A AND B AND C -> [A, B, C]
488        """
489        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
490            if not type(node) is self.__class__:
491                yield node.unnest() if unnest else node
492
493    def __str__(self) -> str:
494        return self.sql()
495
496    def __repr__(self) -> str:
497        return self._to_s()
498
499    def sql(self, dialect: DialectType = None, **opts) -> str:
500        """
501        Returns SQL string representation of this tree.
502
503        Args:
504            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
505            opts: other `sqlglot.generator.Generator` options.
506
507        Returns:
508            The SQL string.
509        """
510        from sqlglot.dialects import Dialect
511
512        return Dialect.get_or_raise(dialect)().generate(self, **opts)
513
514    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
515        indent = "" if not level else "\n"
516        indent += "".join(["  "] * level)
517        left = f"({self.key.upper()} "
518
519        args: t.Dict[str, t.Any] = {
520            k: ", ".join(
521                v._to_s(hide_missing=hide_missing, level=level + 1)
522                if hasattr(v, "_to_s")
523                else str(v)
524                for v in ensure_list(vs)
525                if v is not None
526            )
527            for k, vs in self.args.items()
528        }
529        args["comments"] = self.comments
530        args["type"] = self.type
531        args = {k: v for k, v in args.items() if v or not hide_missing}
532
533        right = ", ".join(f"{k}: {v}" for k, v in args.items())
534        right += ")"
535
536        return indent + left + right
537
538    def transform(self, fun, *args, copy=True, **kwargs):
539        """
540        Recursively visits all tree nodes (excluding already transformed ones)
541        and applies the given transformation function to each node.
542
543        Args:
544            fun (function): a function which takes a node as an argument and returns a
545                new transformed node or the same node without modifications. If the function
546                returns None, then the corresponding node will be removed from the syntax tree.
547            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
548                modified in place.
549
550        Returns:
551            The transformed tree.
552        """
553        node = self.copy() if copy else self
554        new_node = fun(node, *args, **kwargs)
555
556        if new_node is None or not isinstance(new_node, Expression):
557            return new_node
558        if new_node is not node:
559            new_node.parent = node.parent
560            return new_node
561
562        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
563        return new_node
564
565    @t.overload
566    def replace(self, expression: E) -> E:
567        ...
568
569    @t.overload
570    def replace(self, expression: None) -> None:
571        ...
572
573    def replace(self, expression):
574        """
575        Swap out this expression with a new expression.
576
577        For example::
578
579            >>> tree = Select().select("x").from_("tbl")
580            >>> tree.find(Column).replace(Column(this="y"))
581            (COLUMN this: y)
582            >>> tree.sql()
583            'SELECT y FROM tbl'
584
585        Args:
586            expression: new node
587
588        Returns:
589            The new expression or expressions.
590        """
591        if not self.parent:
592            return expression
593
594        parent = self.parent
595        self.parent = None
596
597        replace_children(parent, lambda child: expression if child is self else child)
598        return expression
599
600    def pop(self: E) -> E:
601        """
602        Remove this expression from its AST.
603
604        Returns:
605            The popped expression.
606        """
607        self.replace(None)
608        return self
609
610    def assert_is(self, type_: t.Type[E]) -> E:
611        """
612        Assert that this `Expression` is an instance of `type_`.
613
614        If it is NOT an instance of `type_`, this raises an assertion error.
615        Otherwise, this returns this expression.
616
617        Examples:
618            This is useful for type security in chained expressions:
619
620            >>> import sqlglot
621            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
622            'SELECT x, z FROM y'
623        """
624        assert isinstance(self, type_)
625        return self
626
627    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
628        """
629        Checks if this expression is valid (e.g. all mandatory args are set).
630
631        Args:
632            args: a sequence of values that were used to instantiate a Func expression. This is used
633                to check that the provided arguments don't exceed the function argument limit.
634
635        Returns:
636            A list of error messages for all possible errors that were found.
637        """
638        errors: t.List[str] = []
639
640        for k in self.args:
641            if k not in self.arg_types:
642                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
643        for k, mandatory in self.arg_types.items():
644            v = self.args.get(k)
645            if mandatory and (v is None or (isinstance(v, list) and not v)):
646                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
647
648        if (
649            args
650            and isinstance(self, Func)
651            and len(args) > len(self.arg_types)
652            and not self.is_var_len_args
653        ):
654            errors.append(
655                f"The number of provided arguments ({len(args)}) is greater than "
656                f"the maximum number of supported arguments ({len(self.arg_types)})"
657            )
658
659        return errors
660
661    def dump(self):
662        """
663        Dump this Expression to a JSON-serializable dict.
664        """
665        from sqlglot.serde import dump
666
667        return dump(self)
668
669    @classmethod
670    def load(cls, obj):
671        """
672        Load a dict (as returned by `Expression.dump`) into an Expression instance.
673        """
674        from sqlglot.serde import load
675
676        return load(obj)
677
678    def and_(
679        self,
680        *expressions: t.Optional[ExpOrStr],
681        dialect: DialectType = None,
682        copy: bool = True,
683        **opts,
684    ) -> Condition:
685        """
686        AND this condition with one or multiple expressions.
687
688        Example:
689            >>> condition("x=1").and_("y=1").sql()
690            'x = 1 AND y = 1'
691
692        Args:
693            *expressions: the SQL code strings to parse.
694                If an `Expression` instance is passed, it will be used as-is.
695            dialect: the dialect used to parse the input expression.
696            copy: whether or not to copy the involved expressions (only applies to Expressions).
697            opts: other options to use to parse the input expressions.
698
699        Returns:
700            The new And condition.
701        """
702        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
703
704    def or_(
705        self,
706        *expressions: t.Optional[ExpOrStr],
707        dialect: DialectType = None,
708        copy: bool = True,
709        **opts,
710    ) -> Condition:
711        """
712        OR this condition with one or multiple expressions.
713
714        Example:
715            >>> condition("x=1").or_("y=1").sql()
716            'x = 1 OR y = 1'
717
718        Args:
719            *expressions: the SQL code strings to parse.
720                If an `Expression` instance is passed, it will be used as-is.
721            dialect: the dialect used to parse the input expression.
722            copy: whether or not to copy the involved expressions (only applies to Expressions).
723            opts: other options to use to parse the input expressions.
724
725        Returns:
726            The new Or condition.
727        """
728        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
729
730    def not_(self, copy: bool = True):
731        """
732        Wrap this condition with NOT.
733
734        Example:
735            >>> condition("x=1").not_().sql()
736            'NOT x = 1'
737
738        Args:
739            copy: whether or not to copy this object.
740
741        Returns:
742            The new Not instance.
743        """
744        return not_(self, copy=copy)
745
746    def as_(
747        self,
748        alias: str | Identifier,
749        quoted: t.Optional[bool] = None,
750        dialect: DialectType = None,
751        copy: bool = True,
752        **opts,
753    ) -> Alias:
754        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
755
756    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
757        this = self.copy()
758        other = convert(other, copy=True)
759        if not isinstance(this, klass) and not isinstance(other, klass):
760            this = _wrap(this, Binary)
761            other = _wrap(other, Binary)
762        if reverse:
763            return klass(this=other, expression=this)
764        return klass(this=this, expression=other)
765
766    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]) -> Bracket:
767        return Bracket(
768            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
769        )
770
771    def __iter__(self) -> t.Iterator:
772        if "expressions" in self.arg_types:
773            return iter(self.args.get("expressions") or [])
774        # We define this because __getitem__ converts Expression into an iterable, which is
775        # problematic because one can hit infinite loops if they do "for x in some_expr: ..."
776        # See: https://peps.python.org/pep-0234/
777        raise TypeError(f"'{self.__class__.__name__}' object is not iterable")
778
779    def isin(
780        self,
781        *expressions: t.Any,
782        query: t.Optional[ExpOrStr] = None,
783        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
784        copy: bool = True,
785        **opts,
786    ) -> In:
787        return In(
788            this=maybe_copy(self, copy),
789            expressions=[convert(e, copy=copy) for e in expressions],
790            query=maybe_parse(query, copy=copy, **opts) if query else None,
791            unnest=Unnest(
792                expressions=[
793                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
794                ]
795            )
796            if unnest
797            else None,
798        )
799
800    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
801        return Between(
802            this=maybe_copy(self, copy),
803            low=convert(low, copy=copy, **opts),
804            high=convert(high, copy=copy, **opts),
805        )
806
807    def is_(self, other: ExpOrStr) -> Is:
808        return self._binop(Is, other)
809
810    def like(self, other: ExpOrStr) -> Like:
811        return self._binop(Like, other)
812
813    def ilike(self, other: ExpOrStr) -> ILike:
814        return self._binop(ILike, other)
815
816    def eq(self, other: t.Any) -> EQ:
817        return self._binop(EQ, other)
818
819    def neq(self, other: t.Any) -> NEQ:
820        return self._binop(NEQ, other)
821
822    def rlike(self, other: ExpOrStr) -> RegexpLike:
823        return self._binop(RegexpLike, other)
824
825    def __lt__(self, other: t.Any) -> LT:
826        return self._binop(LT, other)
827
828    def __le__(self, other: t.Any) -> LTE:
829        return self._binop(LTE, other)
830
831    def __gt__(self, other: t.Any) -> GT:
832        return self._binop(GT, other)
833
834    def __ge__(self, other: t.Any) -> GTE:
835        return self._binop(GTE, other)
836
837    def __add__(self, other: t.Any) -> Add:
838        return self._binop(Add, other)
839
840    def __radd__(self, other: t.Any) -> Add:
841        return self._binop(Add, other, reverse=True)
842
843    def __sub__(self, other: t.Any) -> Sub:
844        return self._binop(Sub, other)
845
846    def __rsub__(self, other: t.Any) -> Sub:
847        return self._binop(Sub, other, reverse=True)
848
849    def __mul__(self, other: t.Any) -> Mul:
850        return self._binop(Mul, other)
851
852    def __rmul__(self, other: t.Any) -> Mul:
853        return self._binop(Mul, other, reverse=True)
854
855    def __truediv__(self, other: t.Any) -> Div:
856        return self._binop(Div, other)
857
858    def __rtruediv__(self, other: t.Any) -> Div:
859        return self._binop(Div, other, reverse=True)
860
861    def __floordiv__(self, other: t.Any) -> IntDiv:
862        return self._binop(IntDiv, other)
863
864    def __rfloordiv__(self, other: t.Any) -> IntDiv:
865        return self._binop(IntDiv, other, reverse=True)
866
867    def __mod__(self, other: t.Any) -> Mod:
868        return self._binop(Mod, other)
869
870    def __rmod__(self, other: t.Any) -> Mod:
871        return self._binop(Mod, other, reverse=True)
872
873    def __pow__(self, other: t.Any) -> Pow:
874        return self._binop(Pow, other)
875
876    def __rpow__(self, other: t.Any) -> Pow:
877        return self._binop(Pow, other, reverse=True)
878
879    def __and__(self, other: t.Any) -> And:
880        return self._binop(And, other)
881
882    def __rand__(self, other: t.Any) -> And:
883        return self._binop(And, other, reverse=True)
884
885    def __or__(self, other: t.Any) -> Or:
886        return self._binop(Or, other)
887
888    def __ror__(self, other: t.Any) -> Or:
889        return self._binop(Or, other, reverse=True)
890
891    def __neg__(self) -> Neg:
892        return Neg(this=_wrap(self.copy(), Binary))
893
894    def __invert__(self) -> Not:
895        return not_(self.copy())

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • type: the DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
  • meta: a dictionary that can be used to store useful metadata for a given expression.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
 94    def __init__(self, **args: t.Any):
 95        self.args: t.Dict[str, t.Any] = args
 96        self.parent: t.Optional[Expression] = None
 97        self.arg_key: t.Optional[str] = None
 98        self.comments: t.Optional[t.List[str]] = None
 99        self._type: t.Optional[DataType] = None
100        self._meta: t.Optional[t.Dict[str, t.Any]] = None
101        self._hash: t.Optional[int] = None
102
103        for arg_key, value in self.args.items():
104            self._set_parent(arg_key, value)
key = 'expression'
arg_types = {'this': True}
args: Dict[str, Any]
parent: Optional[Expression]
arg_key: Optional[str]
comments: Optional[List[str]]
hashable_args: Any
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

alias_column_names: List[str]
name: str
alias_or_name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
type: Optional[DataType]
meta: Dict[str, Any]
def copy(self):
261    def copy(self):
262        """
263        Returns a deep copy of the expression.
264        """
265        new = deepcopy(self)
266        new.parent = self.parent
267        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
269    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
270        if self.comments is None:
271            self.comments = []
272        if comments:
273            for comment in comments:
274                _, *meta = comment.split(SQLGLOT_META)
275                if meta:
276                    for kv in "".join(meta).split(","):
277                        k, *v = kv.split("=")
278                        value = v[0].strip() if v else True
279                        self.meta[k.strip()] = value
280                self.comments.append(comment)
def append(self, arg_key: str, value: Any) -> None:
282    def append(self, arg_key: str, value: t.Any) -> None:
283        """
284        Appends value to arg_key if it's a list or sets it as a new list.
285
286        Args:
287            arg_key (str): name of the list expression arg
288            value (Any): value to append to the list
289        """
290        if not isinstance(self.args.get(arg_key), list):
291            self.args[arg_key] = []
292        self.args[arg_key].append(value)
293        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key: str, value: Any) -> None:
295    def set(self, arg_key: str, value: t.Any) -> None:
296        """
297        Sets arg_key to value.
298
299        Args:
300            arg_key: name of the expression arg.
301            value: value to set the arg to.
302        """
303        if value is None:
304            self.args.pop(arg_key, None)
305            return
306
307        self.args[arg_key] = value
308        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key: name of the expression arg.
  • value: value to set the arg to.
depth: int

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, Expression]]:
329    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
330        """Yields the key and expression for all arguments, exploding list args."""
331        for k, vs in self.args.items():
332            if type(vs) is list:
333                for v in vs:
334                    if hasattr(v, "parent"):
335                        yield k, v
336            else:
337                if hasattr(vs, "parent"):
338                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs: bool = True) -> Optional[~E]:
340    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
341        """
342        Returns the first node in this tree which matches at least one of
343        the specified types.
344
345        Args:
346            expression_types: the expression type(s) to match.
347            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
348
349        Returns:
350            The node which matches the criteria or None if no such node was found.
351        """
352        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs: bool = True) -> Iterator[~E]:
354    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
355        """
356        Returns a generator object which visits all nodes in this tree and only
357        yields those that match at least one of the specified expression types.
358
359        Args:
360            expression_types: the expression type(s) to match.
361            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
362
363        Returns:
364            The generator object.
365        """
366        for expression, *_ in self.walk(bfs=bfs):
367            if isinstance(expression, expression_types):
368                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
370    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
371        """
372        Returns a nearest parent matching expression_types.
373
374        Args:
375            expression_types: the expression type(s) to match.
376
377        Returns:
378            The parent node.
379        """
380        ancestor = self.parent
381        while ancestor and not isinstance(ancestor, expression_types):
382            ancestor = ancestor.parent
383        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select: Optional[Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> Expression:
397    def root(self) -> Expression:
398        """
399        Returns the root expression of this tree.
400        """
401        expression = self
402        while expression.parent:
403            expression = expression.parent
404        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
406    def walk(self, bfs=True, prune=None):
407        """
408        Returns a generator object which visits all nodes in this tree.
409
410        Args:
411            bfs (bool): if set to True the BFS traversal order will be applied,
412                otherwise the DFS traversal will be used instead.
413            prune ((node, parent, arg_key) -> bool): callable that returns True if
414                the generator should stop traversing this branch of the tree.
415
416        Returns:
417            the generator object.
418        """
419        if bfs:
420            yield from self.bfs(prune=prune)
421        else:
422            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
424    def dfs(self, parent=None, key=None, prune=None):
425        """
426        Returns a generator object which visits all nodes in this tree in
427        the DFS (Depth-first) order.
428
429        Returns:
430            The generator object.
431        """
432        parent = parent or self.parent
433        yield self, parent, key
434        if prune and prune(self, parent, key):
435            return
436
437        for k, v in self.iter_expressions():
438            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
440    def bfs(self, prune=None):
441        """
442        Returns a generator object which visits all nodes in this tree in
443        the BFS (Breadth-first) order.
444
445        Returns:
446            The generator object.
447        """
448        queue = deque([(self, self.parent, None)])
449
450        while queue:
451            item, parent, key = queue.popleft()
452
453            yield item, parent, key
454            if prune and prune(item, parent, key):
455                continue
456
457            for k, v in item.iter_expressions():
458                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
460    def unnest(self):
461        """
462        Returns the first non parenthesis child or self.
463        """
464        expression = self
465        while type(expression) is Paren:
466            expression = expression.this
467        return expression

Returns the first non parenthesis child or self.

def unalias(self):
469    def unalias(self):
470        """
471        Returns the inner expression if this is an Alias.
472        """
473        if isinstance(self, Alias):
474            return self.this
475        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
477    def unnest_operands(self):
478        """
479        Returns unnested operands as a tuple.
480        """
481        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
483    def flatten(self, unnest=True):
484        """
485        Returns a generator which yields child nodes who's parents are the same class.
486
487        A AND B AND C -> [A, B, C]
488        """
489        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
490            if not type(node) is self.__class__:
491                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
499    def sql(self, dialect: DialectType = None, **opts) -> str:
500        """
501        Returns SQL string representation of this tree.
502
503        Args:
504            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
505            opts: other `sqlglot.generator.Generator` options.
506
507        Returns:
508            The SQL string.
509        """
510        from sqlglot.dialects import Dialect
511
512        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
538    def transform(self, fun, *args, copy=True, **kwargs):
539        """
540        Recursively visits all tree nodes (excluding already transformed ones)
541        and applies the given transformation function to each node.
542
543        Args:
544            fun (function): a function which takes a node as an argument and returns a
545                new transformed node or the same node without modifications. If the function
546                returns None, then the corresponding node will be removed from the syntax tree.
547            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
548                modified in place.
549
550        Returns:
551            The transformed tree.
552        """
553        node = self.copy() if copy else self
554        new_node = fun(node, *args, **kwargs)
555
556        if new_node is None or not isinstance(new_node, Expression):
557            return new_node
558        if new_node is not node:
559            new_node.parent = node.parent
560            return new_node
561
562        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
563        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
573    def replace(self, expression):
574        """
575        Swap out this expression with a new expression.
576
577        For example::
578
579            >>> tree = Select().select("x").from_("tbl")
580            >>> tree.find(Column).replace(Column(this="y"))
581            (COLUMN this: y)
582            >>> tree.sql()
583            'SELECT y FROM tbl'
584
585        Args:
586            expression: new node
587
588        Returns:
589            The new expression or expressions.
590        """
591        if not self.parent:
592            return expression
593
594        parent = self.parent
595        self.parent = None
596
597        replace_children(parent, lambda child: expression if child is self else child)
598        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression: new node
Returns:

The new expression or expressions.

def pop(self: ~E) -> ~E:
600    def pop(self: E) -> E:
601        """
602        Remove this expression from its AST.
603
604        Returns:
605            The popped expression.
606        """
607        self.replace(None)
608        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
610    def assert_is(self, type_: t.Type[E]) -> E:
611        """
612        Assert that this `Expression` is an instance of `type_`.
613
614        If it is NOT an instance of `type_`, this raises an assertion error.
615        Otherwise, this returns this expression.
616
617        Examples:
618            This is useful for type security in chained expressions:
619
620            >>> import sqlglot
621            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
622            'SELECT x, z FROM y'
623        """
624        assert isinstance(self, type_)
625        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
627    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
628        """
629        Checks if this expression is valid (e.g. all mandatory args are set).
630
631        Args:
632            args: a sequence of values that were used to instantiate a Func expression. This is used
633                to check that the provided arguments don't exceed the function argument limit.
634
635        Returns:
636            A list of error messages for all possible errors that were found.
637        """
638        errors: t.List[str] = []
639
640        for k in self.args:
641            if k not in self.arg_types:
642                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
643        for k, mandatory in self.arg_types.items():
644            v = self.args.get(k)
645            if mandatory and (v is None or (isinstance(v, list) and not v)):
646                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
647
648        if (
649            args
650            and isinstance(self, Func)
651            and len(args) > len(self.arg_types)
652            and not self.is_var_len_args
653        ):
654            errors.append(
655                f"The number of provided arguments ({len(args)}) is greater than "
656                f"the maximum number of supported arguments ({len(self.arg_types)})"
657            )
658
659        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
661    def dump(self):
662        """
663        Dump this Expression to a JSON-serializable dict.
664        """
665        from sqlglot.serde import dump
666
667        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
669    @classmethod
670    def load(cls, obj):
671        """
672        Load a dict (as returned by `Expression.dump`) into an Expression instance.
673        """
674        from sqlglot.serde import load
675
676        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

def and_( self, *expressions: Union[str, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
678    def and_(
679        self,
680        *expressions: t.Optional[ExpOrStr],
681        dialect: DialectType = None,
682        copy: bool = True,
683        **opts,
684    ) -> Condition:
685        """
686        AND this condition with one or multiple expressions.
687
688        Example:
689            >>> condition("x=1").and_("y=1").sql()
690            'x = 1 AND y = 1'
691
692        Args:
693            *expressions: the SQL code strings to parse.
694                If an `Expression` instance is passed, it will be used as-is.
695            dialect: the dialect used to parse the input expression.
696            copy: whether or not to copy the involved expressions (only applies to Expressions).
697            opts: other options to use to parse the input expressions.
698
699        Returns:
700            The new And condition.
701        """
702        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

def or_( self, *expressions: Union[str, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
704    def or_(
705        self,
706        *expressions: t.Optional[ExpOrStr],
707        dialect: DialectType = None,
708        copy: bool = True,
709        **opts,
710    ) -> Condition:
711        """
712        OR this condition with one or multiple expressions.
713
714        Example:
715            >>> condition("x=1").or_("y=1").sql()
716            'x = 1 OR y = 1'
717
718        Args:
719            *expressions: the SQL code strings to parse.
720                If an `Expression` instance is passed, it will be used as-is.
721            dialect: the dialect used to parse the input expression.
722            copy: whether or not to copy the involved expressions (only applies to Expressions).
723            opts: other options to use to parse the input expressions.
724
725        Returns:
726            The new Or condition.
727        """
728        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

def not_(self, copy: bool = True):
730    def not_(self, copy: bool = True):
731        """
732        Wrap this condition with NOT.
733
734        Example:
735            >>> condition("x=1").not_().sql()
736            'NOT x = 1'
737
738        Args:
739            copy: whether or not to copy this object.
740
741        Returns:
742            The new Not instance.
743        """
744        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy: whether or not to copy this object.
Returns:

The new Not instance.

def as_( self, alias: str | Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Alias:
746    def as_(
747        self,
748        alias: str | Identifier,
749        quoted: t.Optional[bool] = None,
750        dialect: DialectType = None,
751        copy: bool = True,
752        **opts,
753    ) -> Alias:
754        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, Expression, NoneType] = None, unnest: Union[str, Expression, NoneType, Collection[Union[str, Expression]]] = None, copy: bool = True, **opts) -> In:
779    def isin(
780        self,
781        *expressions: t.Any,
782        query: t.Optional[ExpOrStr] = None,
783        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
784        copy: bool = True,
785        **opts,
786    ) -> In:
787        return In(
788            this=maybe_copy(self, copy),
789            expressions=[convert(e, copy=copy) for e in expressions],
790            query=maybe_parse(query, copy=copy, **opts) if query else None,
791            unnest=Unnest(
792                expressions=[
793                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
794                ]
795            )
796            if unnest
797            else None,
798        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> Between:
800    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
801        return Between(
802            this=maybe_copy(self, copy),
803            low=convert(low, copy=copy, **opts),
804            high=convert(high, copy=copy, **opts),
805        )
def is_( self, other: Union[str, Expression]) -> Is:
807    def is_(self, other: ExpOrStr) -> Is:
808        return self._binop(Is, other)
def like( self, other: Union[str, Expression]) -> Like:
810    def like(self, other: ExpOrStr) -> Like:
811        return self._binop(Like, other)
def ilike( self, other: Union[str, Expression]) -> ILike:
813    def ilike(self, other: ExpOrStr) -> ILike:
814        return self._binop(ILike, other)
def eq(self, other: Any) -> EQ:
816    def eq(self, other: t.Any) -> EQ:
817        return self._binop(EQ, other)
def neq(self, other: Any) -> NEQ:
819    def neq(self, other: t.Any) -> NEQ:
820        return self._binop(NEQ, other)
def rlike( self, other: Union[str, Expression]) -> RegexpLike:
822    def rlike(self, other: ExpOrStr) -> RegexpLike:
823        return self._binop(RegexpLike, other)
IntoType = typing.Union[str, typing.Type[Expression], typing.Collection[typing.Union[str, typing.Type[Expression]]]]
ExpOrStr = typing.Union[str, Expression]
class Condition(Expression):
906class Condition(Expression):
907    """Logical conditions like x AND y, or simply x"""

Logical conditions like x AND y, or simply x

key = 'condition'
class Predicate(Condition):
910class Predicate(Condition):
911    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

key = 'predicate'
class DerivedTable(Expression):
914class DerivedTable(Expression):
915    @property
916    def selects(self) -> t.List[Expression]:
917        return self.this.selects if isinstance(self.this, Subqueryable) else []
918
919    @property
920    def named_selects(self) -> t.List[str]:
921        return [select.output_name for select in self.selects]
selects: List[Expression]
named_selects: List[str]
key = 'derivedtable'
class Unionable(Expression):
924class Unionable(Expression):
925    def union(
926        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
927    ) -> Unionable:
928        """
929        Builds a UNION expression.
930
931        Example:
932            >>> import sqlglot
933            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
934            'SELECT * FROM foo UNION SELECT * FROM bla'
935
936        Args:
937            expression: the SQL code string.
938                If an `Expression` instance is passed, it will be used as-is.
939            distinct: set the DISTINCT flag if and only if this is true.
940            dialect: the dialect used to parse the input expression.
941            opts: other options to use to parse the input expressions.
942
943        Returns:
944            The new Union expression.
945        """
946        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
947
948    def intersect(
949        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
950    ) -> Unionable:
951        """
952        Builds an INTERSECT expression.
953
954        Example:
955            >>> import sqlglot
956            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
957            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
958
959        Args:
960            expression: the SQL code string.
961                If an `Expression` instance is passed, it will be used as-is.
962            distinct: set the DISTINCT flag if and only if this is true.
963            dialect: the dialect used to parse the input expression.
964            opts: other options to use to parse the input expressions.
965
966        Returns:
967            The new Intersect expression.
968        """
969        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
970
971    def except_(
972        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
973    ) -> Unionable:
974        """
975        Builds an EXCEPT expression.
976
977        Example:
978            >>> import sqlglot
979            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
980            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
981
982        Args:
983            expression: the SQL code string.
984                If an `Expression` instance is passed, it will be used as-is.
985            distinct: set the DISTINCT flag if and only if this is true.
986            dialect: the dialect used to parse the input expression.
987            opts: other options to use to parse the input expressions.
988
989        Returns:
990            The new Except expression.
991        """
992        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Unionable:
925    def union(
926        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
927    ) -> Unionable:
928        """
929        Builds a UNION expression.
930
931        Example:
932            >>> import sqlglot
933            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
934            'SELECT * FROM foo UNION SELECT * FROM bla'
935
936        Args:
937            expression: the SQL code string.
938                If an `Expression` instance is passed, it will be used as-is.
939            distinct: set the DISTINCT flag if and only if this is true.
940            dialect: the dialect used to parse the input expression.
941            opts: other options to use to parse the input expressions.
942
943        Returns:
944            The new Union expression.
945        """
946        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union expression.

def intersect( self, expression: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Unionable:
948    def intersect(
949        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
950    ) -> Unionable:
951        """
952        Builds an INTERSECT expression.
953
954        Example:
955            >>> import sqlglot
956            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
957            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
958
959        Args:
960            expression: the SQL code string.
961                If an `Expression` instance is passed, it will be used as-is.
962            distinct: set the DISTINCT flag if and only if this is true.
963            dialect: the dialect used to parse the input expression.
964            opts: other options to use to parse the input expressions.
965
966        Returns:
967            The new Intersect expression.
968        """
969        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect expression.

def except_( self, expression: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Unionable:
971    def except_(
972        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
973    ) -> Unionable:
974        """
975        Builds an EXCEPT expression.
976
977        Example:
978            >>> import sqlglot
979            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
980            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
981
982        Args:
983            expression: the SQL code string.
984                If an `Expression` instance is passed, it will be used as-is.
985            distinct: set the DISTINCT flag if and only if this is true.
986            dialect: the dialect used to parse the input expression.
987            opts: other options to use to parse the input expressions.
988
989        Returns:
990            The new Except expression.
991        """
992        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except expression.

key = 'unionable'
class UDTF(DerivedTable, Unionable):
995class UDTF(DerivedTable, Unionable):
996    @property
997    def selects(self) -> t.List[Expression]:
998        alias = self.args.get("alias")
999        return alias.columns if alias else []
selects: List[Expression]
key = 'udtf'
class Cache(Expression):
1002class Cache(Expression):
1003    arg_types = {
1004        "with": False,
1005        "this": True,
1006        "lazy": False,
1007        "options": False,
1008        "expression": False,
1009    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
1012class Uncache(Expression):
1013    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class DDL(Expression):
1016class DDL(Expression):
1017    @property
1018    def ctes(self):
1019        with_ = self.args.get("with")
1020        if not with_:
1021            return []
1022        return with_.expressions
1023
1024    @property
1025    def named_selects(self) -> t.List[str]:
1026        if isinstance(self.expression, Subqueryable):
1027            return self.expression.named_selects
1028        return []
1029
1030    @property
1031    def selects(self) -> t.List[Expression]:
1032        if isinstance(self.expression, Subqueryable):
1033            return self.expression.selects
1034        return []
ctes
named_selects: List[str]
selects: List[Expression]
key = 'ddl'
class Create(DDL):
1037class Create(DDL):
1038    arg_types = {
1039        "with": False,
1040        "this": True,
1041        "kind": True,
1042        "expression": False,
1043        "exists": False,
1044        "properties": False,
1045        "replace": False,
1046        "unique": False,
1047        "indexes": False,
1048        "no_schema_binding": False,
1049        "begin": False,
1050        "end": False,
1051        "clone": False,
1052    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'end': False, 'clone': False}
key = 'create'
class Clone(Expression):
1058class Clone(Expression):
1059    arg_types = {
1060        "this": True,
1061        "when": False,
1062        "kind": False,
1063        "shallow": False,
1064        "expression": False,
1065        "copy": False,
1066    }
arg_types = {'this': True, 'when': False, 'kind': False, 'shallow': False, 'expression': False, 'copy': False}
key = 'clone'
class Describe(Expression):
1069class Describe(Expression):
1070    arg_types = {"this": True, "kind": False, "expressions": False}
arg_types = {'this': True, 'kind': False, 'expressions': False}
key = 'describe'
class Kill(Expression):
1073class Kill(Expression):
1074    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'kill'
class Pragma(Expression):
1077class Pragma(Expression):
1078    pass
key = 'pragma'
class Set(Expression):
1081class Set(Expression):
1082    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1085class SetItem(Expression):
1086    arg_types = {
1087        "this": False,
1088        "expressions": False,
1089        "kind": False,
1090        "collate": False,  # MySQL SET NAMES statement
1091        "global": False,
1092    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1095class Show(Expression):
1096    arg_types = {
1097        "this": True,
1098        "target": False,
1099        "offset": False,
1100        "limit": False,
1101        "like": False,
1102        "where": False,
1103        "db": False,
1104        "scope": False,
1105        "scope_kind": False,
1106        "full": False,
1107        "mutex": False,
1108        "query": False,
1109        "channel": False,
1110        "global": False,
1111        "log": False,
1112        "position": False,
1113        "types": False,
1114    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'scope': False, 'scope_kind': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1117class UserDefinedFunction(Expression):
1118    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1121class CharacterSet(Expression):
1122    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1125class With(Expression):
1126    arg_types = {"expressions": True, "recursive": False}
1127
1128    @property
1129    def recursive(self) -> bool:
1130        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1133class WithinGroup(Expression):
1134    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1137class CTE(DerivedTable):
1138    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1141class TableAlias(Expression):
1142    arg_types = {"this": False, "columns": False}
1143
1144    @property
1145    def columns(self):
1146        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1149class BitString(Condition):
1150    pass
key = 'bitstring'
class HexString(Condition):
1153class HexString(Condition):
1154    pass
key = 'hexstring'
class ByteString(Condition):
1157class ByteString(Condition):
1158    pass
key = 'bytestring'
class RawString(Condition):
1161class RawString(Condition):
1162    pass
key = 'rawstring'
class Column(Condition):
1165class Column(Condition):
1166    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1167
1168    @property
1169    def table(self) -> str:
1170        return self.text("table")
1171
1172    @property
1173    def db(self) -> str:
1174        return self.text("db")
1175
1176    @property
1177    def catalog(self) -> str:
1178        return self.text("catalog")
1179
1180    @property
1181    def output_name(self) -> str:
1182        return self.name
1183
1184    @property
1185    def parts(self) -> t.List[Identifier]:
1186        """Return the parts of a column in order catalog, db, table, name."""
1187        return [
1188            t.cast(Identifier, self.args[part])
1189            for part in ("catalog", "db", "table", "this")
1190            if self.args.get(part)
1191        ]
1192
1193    def to_dot(self) -> Dot | Identifier:
1194        """Converts the column into a dot expression."""
1195        parts = self.parts
1196        parent = self.parent
1197
1198        while parent:
1199            if isinstance(parent, Dot):
1200                parts.append(parent.expression)
1201            parent = parent.parent
1202
1203        return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
parts: List[Identifier]

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> Dot | Identifier:
1193    def to_dot(self) -> Dot | Identifier:
1194        """Converts the column into a dot expression."""
1195        parts = self.parts
1196        parent = self.parent
1197
1198        while parent:
1199            if isinstance(parent, Dot):
1200                parts.append(parent.expression)
1201            parent = parent.parent
1202
1203        return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1206class ColumnPosition(Expression):
1207    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1210class ColumnDef(Expression):
1211    arg_types = {
1212        "this": True,
1213        "kind": False,
1214        "constraints": False,
1215        "exists": False,
1216        "position": False,
1217    }
1218
1219    @property
1220    def constraints(self) -> t.List[ColumnConstraint]:
1221        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
constraints: List[ColumnConstraint]
key = 'columndef'
class AlterColumn(Expression):
1224class AlterColumn(Expression):
1225    arg_types = {
1226        "this": True,
1227        "dtype": False,
1228        "collate": False,
1229        "using": False,
1230        "default": False,
1231        "drop": False,
1232    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1235class RenameTable(Expression):
1236    pass
key = 'renametable'
class Comment(Expression):
1239class Comment(Expression):
1240    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class Comprehension(Expression):
1243class Comprehension(Expression):
1244    arg_types = {"this": True, "expression": True, "iterator": True, "condition": False}
arg_types = {'this': True, 'expression': True, 'iterator': True, 'condition': False}
key = 'comprehension'
class MergeTreeTTLAction(Expression):
1248class MergeTreeTTLAction(Expression):
1249    arg_types = {
1250        "this": True,
1251        "delete": False,
1252        "recompress": False,
1253        "to_disk": False,
1254        "to_volume": False,
1255    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1259class MergeTreeTTL(Expression):
1260    arg_types = {
1261        "expressions": True,
1262        "where": False,
1263        "group": False,
1264        "aggregates": False,
1265    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1269class IndexConstraintOption(Expression):
1270    arg_types = {
1271        "key_block_size": False,
1272        "using": False,
1273        "parser": False,
1274        "comment": False,
1275        "visible": False,
1276        "engine_attr": False,
1277        "secondary_engine_attr": False,
1278    }
arg_types = {'key_block_size': False, 'using': False, 'parser': False, 'comment': False, 'visible': False, 'engine_attr': False, 'secondary_engine_attr': False}
key = 'indexconstraintoption'
class ColumnConstraint(Expression):
1281class ColumnConstraint(Expression):
1282    arg_types = {"this": False, "kind": True}
1283
1284    @property
1285    def kind(self) -> ColumnConstraintKind:
1286        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1289class ColumnConstraintKind(Expression):
1290    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1293class AutoIncrementColumnConstraint(ColumnConstraintKind):
1294    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1297class CaseSpecificColumnConstraint(ColumnConstraintKind):
1298    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1301class CharacterSetColumnConstraint(ColumnConstraintKind):
1302    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1305class CheckColumnConstraint(ColumnConstraintKind):
1306    pass
key = 'checkcolumnconstraint'
class ClusteredColumnConstraint(ColumnConstraintKind):
1309class ClusteredColumnConstraint(ColumnConstraintKind):
1310    pass
key = 'clusteredcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1313class CollateColumnConstraint(ColumnConstraintKind):
1314    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1317class CommentColumnConstraint(ColumnConstraintKind):
1318    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1321class CompressColumnConstraint(ColumnConstraintKind):
1322    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1325class DateFormatColumnConstraint(ColumnConstraintKind):
1326    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1329class DefaultColumnConstraint(ColumnConstraintKind):
1330    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1333class EncodeColumnConstraint(ColumnConstraintKind):
1334    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1337class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1338    # this: True -> ALWAYS, this: False -> BY DEFAULT
1339    arg_types = {
1340        "this": False,
1341        "expression": False,
1342        "on_null": False,
1343        "start": False,
1344        "increment": False,
1345        "minvalue": False,
1346        "maxvalue": False,
1347        "cycle": False,
1348    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1352class IndexColumnConstraint(ColumnConstraintKind):
1353    arg_types = {
1354        "this": False,
1355        "schema": True,
1356        "kind": False,
1357        "index_type": False,
1358        "options": False,
1359    }
arg_types = {'this': False, 'schema': True, 'kind': False, 'index_type': False, 'options': False}
key = 'indexcolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1362class InlineLengthColumnConstraint(ColumnConstraintKind):
1363    pass
key = 'inlinelengthcolumnconstraint'
class NonClusteredColumnConstraint(ColumnConstraintKind):
1366class NonClusteredColumnConstraint(ColumnConstraintKind):
1367    pass
key = 'nonclusteredcolumnconstraint'
class NotForReplicationColumnConstraint(ColumnConstraintKind):
1370class NotForReplicationColumnConstraint(ColumnConstraintKind):
1371    arg_types = {}
arg_types = {}
key = 'notforreplicationcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1374class NotNullColumnConstraint(ColumnConstraintKind):
1375    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1379class OnUpdateColumnConstraint(ColumnConstraintKind):
1380    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1383class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1384    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1387class TitleColumnConstraint(ColumnConstraintKind):
1388    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1391class UniqueColumnConstraint(ColumnConstraintKind):
1392    arg_types = {"this": False, "index_type": False}
arg_types = {'this': False, 'index_type': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1395class UppercaseColumnConstraint(ColumnConstraintKind):
1396    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1399class PathColumnConstraint(ColumnConstraintKind):
1400    pass
key = 'pathcolumnconstraint'
class ComputedColumnConstraint(ColumnConstraintKind):
1405class ComputedColumnConstraint(ColumnConstraintKind):
1406    arg_types = {"this": True, "persisted": False, "not_null": False}
arg_types = {'this': True, 'persisted': False, 'not_null': False}
key = 'computedcolumnconstraint'
class Constraint(Expression):
1409class Constraint(Expression):
1410    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1413class Delete(Expression):
1414    arg_types = {
1415        "with": False,
1416        "this": False,
1417        "using": False,
1418        "where": False,
1419        "returning": False,
1420        "limit": False,
1421        "tables": False,  # Multiple-Table Syntax (MySQL)
1422    }
1423
1424    def delete(
1425        self,
1426        table: ExpOrStr,
1427        dialect: DialectType = None,
1428        copy: bool = True,
1429        **opts,
1430    ) -> Delete:
1431        """
1432        Create a DELETE expression or replace the table on an existing DELETE expression.
1433
1434        Example:
1435            >>> delete("tbl").sql()
1436            'DELETE FROM tbl'
1437
1438        Args:
1439            table: the table from which to delete.
1440            dialect: the dialect used to parse the input expression.
1441            copy: if `False`, modify this expression instance in-place.
1442            opts: other options to use to parse the input expressions.
1443
1444        Returns:
1445            Delete: the modified expression.
1446        """
1447        return _apply_builder(
1448            expression=table,
1449            instance=self,
1450            arg="this",
1451            dialect=dialect,
1452            into=Table,
1453            copy=copy,
1454            **opts,
1455        )
1456
1457    def where(
1458        self,
1459        *expressions: t.Optional[ExpOrStr],
1460        append: bool = True,
1461        dialect: DialectType = None,
1462        copy: bool = True,
1463        **opts,
1464    ) -> Delete:
1465        """
1466        Append to or set the WHERE expressions.
1467
1468        Example:
1469            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1470            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1471
1472        Args:
1473            *expressions: the SQL code strings to parse.
1474                If an `Expression` instance is passed, it will be used as-is.
1475                Multiple expressions are combined with an AND operator.
1476            append: if `True`, AND the new expressions to any existing expression.
1477                Otherwise, this resets the expression.
1478            dialect: the dialect used to parse the input expressions.
1479            copy: if `False`, modify this expression instance in-place.
1480            opts: other options to use to parse the input expressions.
1481
1482        Returns:
1483            Delete: the modified expression.
1484        """
1485        return _apply_conjunction_builder(
1486            *expressions,
1487            instance=self,
1488            arg="where",
1489            append=append,
1490            into=Where,
1491            dialect=dialect,
1492            copy=copy,
1493            **opts,
1494        )
1495
1496    def returning(
1497        self,
1498        expression: ExpOrStr,
1499        dialect: DialectType = None,
1500        copy: bool = True,
1501        **opts,
1502    ) -> Delete:
1503        """
1504        Set the RETURNING expression. Not supported by all dialects.
1505
1506        Example:
1507            >>> delete("tbl").returning("*", dialect="postgres").sql()
1508            'DELETE FROM tbl RETURNING *'
1509
1510        Args:
1511            expression: the SQL code strings to parse.
1512                If an `Expression` instance is passed, it will be used as-is.
1513            dialect: the dialect used to parse the input expressions.
1514            copy: if `False`, modify this expression instance in-place.
1515            opts: other options to use to parse the input expressions.
1516
1517        Returns:
1518            Delete: the modified expression.
1519        """
1520        return _apply_builder(
1521            expression=expression,
1522            instance=self,
1523            arg="returning",
1524            prefix="RETURNING",
1525            dialect=dialect,
1526            copy=copy,
1527            into=Returning,
1528            **opts,
1529        )
arg_types = {'with': False, 'this': False, 'using': False, 'where': False, 'returning': False, 'limit': False, 'tables': False}
def delete( self, table: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Delete:
1424    def delete(
1425        self,
1426        table: ExpOrStr,
1427        dialect: DialectType = None,
1428        copy: bool = True,
1429        **opts,
1430    ) -> Delete:
1431        """
1432        Create a DELETE expression or replace the table on an existing DELETE expression.
1433
1434        Example:
1435            >>> delete("tbl").sql()
1436            'DELETE FROM tbl'
1437
1438        Args:
1439            table: the table from which to delete.
1440            dialect: the dialect used to parse the input expression.
1441            copy: if `False`, modify this expression instance in-place.
1442            opts: other options to use to parse the input expressions.
1443
1444        Returns:
1445            Delete: the modified expression.
1446        """
1447        return _apply_builder(
1448            expression=table,
1449            instance=self,
1450            arg="this",
1451            dialect=dialect,
1452            into=Table,
1453            copy=copy,
1454            **opts,
1455        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Delete:
1457    def where(
1458        self,
1459        *expressions: t.Optional[ExpOrStr],
1460        append: bool = True,
1461        dialect: DialectType = None,
1462        copy: bool = True,
1463        **opts,
1464    ) -> Delete:
1465        """
1466        Append to or set the WHERE expressions.
1467
1468        Example:
1469            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1470            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1471
1472        Args:
1473            *expressions: the SQL code strings to parse.
1474                If an `Expression` instance is passed, it will be used as-is.
1475                Multiple expressions are combined with an AND operator.
1476            append: if `True`, AND the new expressions to any existing expression.
1477                Otherwise, this resets the expression.
1478            dialect: the dialect used to parse the input expressions.
1479            copy: if `False`, modify this expression instance in-place.
1480            opts: other options to use to parse the input expressions.
1481
1482        Returns:
1483            Delete: the modified expression.
1484        """
1485        return _apply_conjunction_builder(
1486            *expressions,
1487            instance=self,
1488            arg="where",
1489            append=append,
1490            into=Where,
1491            dialect=dialect,
1492            copy=copy,
1493            **opts,
1494        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Delete:
1496    def returning(
1497        self,
1498        expression: ExpOrStr,
1499        dialect: DialectType = None,
1500        copy: bool = True,
1501        **opts,
1502    ) -> Delete:
1503        """
1504        Set the RETURNING expression. Not supported by all dialects.
1505
1506        Example:
1507            >>> delete("tbl").returning("*", dialect="postgres").sql()
1508            'DELETE FROM tbl RETURNING *'
1509
1510        Args:
1511            expression: the SQL code strings to parse.
1512                If an `Expression` instance is passed, it will be used as-is.
1513            dialect: the dialect used to parse the input expressions.
1514            copy: if `False`, modify this expression instance in-place.
1515            opts: other options to use to parse the input expressions.
1516
1517        Returns:
1518            Delete: the modified expression.
1519        """
1520        return _apply_builder(
1521            expression=expression,
1522            instance=self,
1523            arg="returning",
1524            prefix="RETURNING",
1525            dialect=dialect,
1526            copy=copy,
1527            into=Returning,
1528            **opts,
1529        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

key = 'delete'
class Drop(Expression):
1532class Drop(Expression):
1533    arg_types = {
1534        "this": False,
1535        "kind": False,
1536        "exists": False,
1537        "temporary": False,
1538        "materialized": False,
1539        "cascade": False,
1540        "constraints": False,
1541        "purge": False,
1542    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1545class Filter(Expression):
1546    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1549class Check(Expression):
1550    pass
key = 'check'
class Connect(Expression):
1554class Connect(Expression):
1555    arg_types = {"start": False, "connect": True}
arg_types = {'start': False, 'connect': True}
key = 'connect'
class Prior(Expression):
1558class Prior(Expression):
1559    pass
key = 'prior'
class Directory(Expression):
1562class Directory(Expression):
1563    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1564    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1567class ForeignKey(Expression):
1568    arg_types = {
1569        "expressions": True,
1570        "reference": False,
1571        "delete": False,
1572        "update": False,
1573    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class ColumnPrefix(Expression):
1576class ColumnPrefix(Expression):
1577    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'columnprefix'
class PrimaryKey(Expression):
1580class PrimaryKey(Expression):
1581    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1586class Into(Expression):
1587    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1590class From(Expression):
1591    @property
1592    def name(self) -> str:
1593        return self.this.name
1594
1595    @property
1596    def alias_or_name(self) -> str:
1597        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1600class Having(Expression):
1601    pass
key = 'having'
class Hint(Expression):
1604class Hint(Expression):
1605    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1608class JoinHint(Expression):
1609    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1612class Identifier(Expression):
1613    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1614
1615    @property
1616    def quoted(self) -> bool:
1617        return bool(self.args.get("quoted"))
1618
1619    @property
1620    def hashable_args(self) -> t.Any:
1621        return (self.this, self.quoted)
1622
1623    @property
1624    def output_name(self) -> str:
1625        return self.name
arg_types = {'this': True, 'quoted': False, 'global': False, 'temporary': False}
quoted: bool
hashable_args: Any
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'identifier'
class Opclass(Expression):
1629class Opclass(Expression):
1630    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'opclass'
class Index(Expression):
1633class Index(Expression):
1634    arg_types = {
1635        "this": False,
1636        "table": False,
1637        "using": False,
1638        "where": False,
1639        "columns": False,
1640        "unique": False,
1641        "primary": False,
1642        "amp": False,  # teradata
1643        "partition_by": False,  # teradata
1644        "where": False,  # postgres partial indexes
1645    }
arg_types = {'this': False, 'table': False, 'using': False, 'where': False, 'columns': False, 'unique': False, 'primary': False, 'amp': False, 'partition_by': False}
key = 'index'
class Insert(DDL):
1648class Insert(DDL):
1649    arg_types = {
1650        "with": False,
1651        "this": True,
1652        "expression": False,
1653        "conflict": False,
1654        "returning": False,
1655        "overwrite": False,
1656        "exists": False,
1657        "partition": False,
1658        "alternative": False,
1659        "where": False,
1660        "ignore": False,
1661        "by_name": False,
1662    }
1663
1664    def with_(
1665        self,
1666        alias: ExpOrStr,
1667        as_: ExpOrStr,
1668        recursive: t.Optional[bool] = None,
1669        append: bool = True,
1670        dialect: DialectType = None,
1671        copy: bool = True,
1672        **opts,
1673    ) -> Insert:
1674        """
1675        Append to or set the common table expressions.
1676
1677        Example:
1678            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1679            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1680
1681        Args:
1682            alias: the SQL code string to parse as the table name.
1683                If an `Expression` instance is passed, this is used as-is.
1684            as_: the SQL code string to parse as the table expression.
1685                If an `Expression` instance is passed, it will be used as-is.
1686            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1687            append: if `True`, add to any existing expressions.
1688                Otherwise, this resets the expressions.
1689            dialect: the dialect used to parse the input expression.
1690            copy: if `False`, modify this expression instance in-place.
1691            opts: other options to use to parse the input expressions.
1692
1693        Returns:
1694            The modified expression.
1695        """
1696        return _apply_cte_builder(
1697            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1698        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': False, 'ignore': False, 'by_name': False}
def with_( self, alias: Union[str, Expression], as_: Union[str, Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Insert:
1664    def with_(
1665        self,
1666        alias: ExpOrStr,
1667        as_: ExpOrStr,
1668        recursive: t.Optional[bool] = None,
1669        append: bool = True,
1670        dialect: DialectType = None,
1671        copy: bool = True,
1672        **opts,
1673    ) -> Insert:
1674        """
1675        Append to or set the common table expressions.
1676
1677        Example:
1678            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1679            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1680
1681        Args:
1682            alias: the SQL code string to parse as the table name.
1683                If an `Expression` instance is passed, this is used as-is.
1684            as_: the SQL code string to parse as the table expression.
1685                If an `Expression` instance is passed, it will be used as-is.
1686            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1687            append: if `True`, add to any existing expressions.
1688                Otherwise, this resets the expressions.
1689            dialect: the dialect used to parse the input expression.
1690            copy: if `False`, modify this expression instance in-place.
1691            opts: other options to use to parse the input expressions.
1692
1693        Returns:
1694            The modified expression.
1695        """
1696        return _apply_cte_builder(
1697            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1698        )

Append to or set the common table expressions.

Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'insert'
class OnConflict(Expression):
1701class OnConflict(Expression):
1702    arg_types = {
1703        "duplicate": False,
1704        "expressions": False,
1705        "nothing": False,
1706        "key": False,
1707        "constraint": False,
1708    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1711class Returning(Expression):
1712    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1716class Introducer(Expression):
1717    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1721class National(Expression):
1722    pass
key = 'national'
class LoadData(Expression):
1725class LoadData(Expression):
1726    arg_types = {
1727        "this": True,
1728        "local": False,
1729        "overwrite": False,
1730        "inpath": True,
1731        "partition": False,
1732        "input_format": False,
1733        "serde": False,
1734    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1737class Partition(Expression):
1738    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1741class Fetch(Expression):
1742    arg_types = {
1743        "direction": False,
1744        "count": False,
1745        "percent": False,
1746        "with_ties": False,
1747    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1750class Group(Expression):
1751    arg_types = {
1752        "expressions": False,
1753        "grouping_sets": False,
1754        "cube": False,
1755        "rollup": False,
1756        "totals": False,
1757        "all": False,
1758    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1761class Lambda(Expression):
1762    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1765class Limit(Expression):
1766    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1769class Literal(Condition):
1770    arg_types = {"this": True, "is_string": True}
1771
1772    @property
1773    def hashable_args(self) -> t.Any:
1774        return (self.this, self.args.get("is_string"))
1775
1776    @classmethod
1777    def number(cls, number) -> Literal:
1778        return cls(this=str(number), is_string=False)
1779
1780    @classmethod
1781    def string(cls, string) -> Literal:
1782        return cls(this=str(string), is_string=True)
1783
1784    @property
1785    def output_name(self) -> str:
1786        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> Literal:
1776    @classmethod
1777    def number(cls, number) -> Literal:
1778        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> Literal:
1780    @classmethod
1781    def string(cls, string) -> Literal:
1782        return cls(this=str(string), is_string=True)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1789class Join(Expression):
1790    arg_types = {
1791        "this": True,
1792        "on": False,
1793        "side": False,
1794        "kind": False,
1795        "using": False,
1796        "method": False,
1797        "global": False,
1798        "hint": False,
1799    }
1800
1801    @property
1802    def method(self) -> str:
1803        return self.text("method").upper()
1804
1805    @property
1806    def kind(self) -> str:
1807        return self.text("kind").upper()
1808
1809    @property
1810    def side(self) -> str:
1811        return self.text("side").upper()
1812
1813    @property
1814    def hint(self) -> str:
1815        return self.text("hint").upper()
1816
1817    @property
1818    def alias_or_name(self) -> str:
1819        return self.this.alias_or_name
1820
1821    def on(
1822        self,
1823        *expressions: t.Optional[ExpOrStr],
1824        append: bool = True,
1825        dialect: DialectType = None,
1826        copy: bool = True,
1827        **opts,
1828    ) -> Join:
1829        """
1830        Append to or set the ON expressions.
1831
1832        Example:
1833            >>> import sqlglot
1834            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1835            'JOIN x ON y = 1'
1836
1837        Args:
1838            *expressions: the SQL code strings to parse.
1839                If an `Expression` instance is passed, it will be used as-is.
1840                Multiple expressions are combined with an AND operator.
1841            append: if `True`, AND the new expressions to any existing expression.
1842                Otherwise, this resets the expression.
1843            dialect: the dialect used to parse the input expressions.
1844            copy: if `False`, modify this expression instance in-place.
1845            opts: other options to use to parse the input expressions.
1846
1847        Returns:
1848            The modified Join expression.
1849        """
1850        join = _apply_conjunction_builder(
1851            *expressions,
1852            instance=self,
1853            arg="on",
1854            append=append,
1855            dialect=dialect,
1856            copy=copy,
1857            **opts,
1858        )
1859
1860        if join.kind == "CROSS":
1861            join.set("kind", None)
1862
1863        return join
1864
1865    def using(
1866        self,
1867        *expressions: t.Optional[ExpOrStr],
1868        append: bool = True,
1869        dialect: DialectType = None,
1870        copy: bool = True,
1871        **opts,
1872    ) -> Join:
1873        """
1874        Append to or set the USING expressions.
1875
1876        Example:
1877            >>> import sqlglot
1878            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1879            'JOIN x USING (foo, bla)'
1880
1881        Args:
1882            *expressions: the SQL code strings to parse.
1883                If an `Expression` instance is passed, it will be used as-is.
1884            append: if `True`, concatenate the new expressions to the existing "using" list.
1885                Otherwise, this resets the expression.
1886            dialect: the dialect used to parse the input expressions.
1887            copy: if `False`, modify this expression instance in-place.
1888            opts: other options to use to parse the input expressions.
1889
1890        Returns:
1891            The modified Join expression.
1892        """
1893        join = _apply_list_builder(
1894            *expressions,
1895            instance=self,
1896            arg="using",
1897            append=append,
1898            dialect=dialect,
1899            copy=copy,
1900            **opts,
1901        )
1902
1903        if join.kind == "CROSS":
1904            join.set("kind", None)
1905
1906        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global': False, 'hint': False}
method: str
kind: str
side: str
hint: str
alias_or_name: str
def on( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Join:
1821    def on(
1822        self,
1823        *expressions: t.Optional[ExpOrStr],
1824        append: bool = True,
1825        dialect: DialectType = None,
1826        copy: bool = True,
1827        **opts,
1828    ) -> Join:
1829        """
1830        Append to or set the ON expressions.
1831
1832        Example:
1833            >>> import sqlglot
1834            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1835            'JOIN x ON y = 1'
1836
1837        Args:
1838            *expressions: the SQL code strings to parse.
1839                If an `Expression` instance is passed, it will be used as-is.
1840                Multiple expressions are combined with an AND operator.
1841            append: if `True`, AND the new expressions to any existing expression.
1842                Otherwise, this resets the expression.
1843            dialect: the dialect used to parse the input expressions.
1844            copy: if `False`, modify this expression instance in-place.
1845            opts: other options to use to parse the input expressions.
1846
1847        Returns:
1848            The modified Join expression.
1849        """
1850        join = _apply_conjunction_builder(
1851            *expressions,
1852            instance=self,
1853            arg="on",
1854            append=append,
1855            dialect=dialect,
1856            copy=copy,
1857            **opts,
1858        )
1859
1860        if join.kind == "CROSS":
1861            join.set("kind", None)
1862
1863        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Join:
1865    def using(
1866        self,
1867        *expressions: t.Optional[ExpOrStr],
1868        append: bool = True,
1869        dialect: DialectType = None,
1870        copy: bool = True,
1871        **opts,
1872    ) -> Join:
1873        """
1874        Append to or set the USING expressions.
1875
1876        Example:
1877            >>> import sqlglot
1878            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1879            'JOIN x USING (foo, bla)'
1880
1881        Args:
1882            *expressions: the SQL code strings to parse.
1883                If an `Expression` instance is passed, it will be used as-is.
1884            append: if `True`, concatenate the new expressions to the existing "using" list.
1885                Otherwise, this resets the expression.
1886            dialect: the dialect used to parse the input expressions.
1887            copy: if `False`, modify this expression instance in-place.
1888            opts: other options to use to parse the input expressions.
1889
1890        Returns:
1891            The modified Join expression.
1892        """
1893        join = _apply_list_builder(
1894            *expressions,
1895            instance=self,
1896            arg="using",
1897            append=append,
1898            dialect=dialect,
1899            copy=copy,
1900            **opts,
1901        )
1902
1903        if join.kind == "CROSS":
1904            join.set("kind", None)
1905
1906        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

key = 'join'
class Lateral(UDTF):
1909class Lateral(UDTF):
1910    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1913class MatchRecognize(Expression):
1914    arg_types = {
1915        "partition_by": False,
1916        "order": False,
1917        "measures": False,
1918        "rows": False,
1919        "after": False,
1920        "pattern": False,
1921        "define": False,
1922        "alias": False,
1923    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1928class Final(Expression):
1929    pass
key = 'final'
class Offset(Expression):
1932class Offset(Expression):
1933    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1936class Order(Expression):
1937    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1942class Cluster(Order):
1943    pass
key = 'cluster'
class Distribute(Order):
1946class Distribute(Order):
1947    pass
key = 'distribute'
class Sort(Order):
1950class Sort(Order):
1951    pass
key = 'sort'
class Ordered(Expression):
1954class Ordered(Expression):
1955    arg_types = {"this": True, "desc": False, "nulls_first": True}
arg_types = {'this': True, 'desc': False, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1958class Property(Expression):
1959    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1962class AlgorithmProperty(Property):
1963    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1966class AutoIncrementProperty(Property):
1967    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1970class BlockCompressionProperty(Property):
1971    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1974class CharacterSetProperty(Property):
1975    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1978class ChecksumProperty(Property):
1979    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1982class CollateProperty(Property):
1983    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1986class CopyGrantsProperty(Property):
1987    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1990class DataBlocksizeProperty(Property):
1991    arg_types = {
1992        "size": False,
1993        "units": False,
1994        "minimum": False,
1995        "maximum": False,
1996        "default": False,
1997    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
2000class DefinerProperty(Property):
2001    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
2004class DistKeyProperty(Property):
2005    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
2008class DistStyleProperty(Property):
2009    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
2012class EngineProperty(Property):
2013    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
2016class HeapProperty(Property):
2017    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
2020class ToTableProperty(Property):
2021    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
2024class ExecuteAsProperty(Property):
2025    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
2028class ExternalProperty(Property):
2029    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
2032class FallbackProperty(Property):
2033    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
2036class FileFormatProperty(Property):
2037    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
2040class FreespaceProperty(Property):
2041    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
2044class InputOutputFormat(Expression):
2045    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
2048class IsolatedLoadingProperty(Property):
2049    arg_types = {
2050        "no": True,
2051        "concurrent": True,
2052        "for_all": True,
2053        "for_insert": True,
2054        "for_none": True,
2055    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
2058class JournalProperty(Property):
2059    arg_types = {
2060        "no": False,
2061        "dual": False,
2062        "before": False,
2063        "local": False,
2064        "after": False,
2065    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
2068class LanguageProperty(Property):
2069    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
2073class ClusteredByProperty(Property):
2074    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2077class DictProperty(Property):
2078    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2081class DictSubProperty(Property):
2082    pass
key = 'dictsubproperty'
class DictRange(Property):
2085class DictRange(Property):
2086    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2091class OnCluster(Property):
2092    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2095class LikeProperty(Property):
2096    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2099class LocationProperty(Property):
2100    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2103class LockingProperty(Property):
2104    arg_types = {
2105        "this": False,
2106        "kind": True,
2107        "for_or_in": True,
2108        "lock_type": True,
2109        "override": False,
2110    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2113class LogProperty(Property):
2114    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2117class MaterializedProperty(Property):
2118    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2121class MergeBlockRatioProperty(Property):
2122    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
2125class NoPrimaryIndexProperty(Property):
2126    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnProperty(Property):
2129class OnProperty(Property):
2130    arg_types = {"this": True}
arg_types = {'this': True}
key = 'onproperty'
class OnCommitProperty(Property):
2133class OnCommitProperty(Property):
2134    arg_types = {"delete": False}
arg_types = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2137class PartitionedByProperty(Property):
2138    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2141class ReturnsProperty(Property):
2142    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2145class RowFormatProperty(Property):
2146    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2149class RowFormatDelimitedProperty(Property):
2150    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2151    arg_types = {
2152        "fields": False,
2153        "escaped": False,
2154        "collection_items": False,
2155        "map_keys": False,
2156        "lines": False,
2157        "null": False,
2158        "serde": False,
2159    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2162class RowFormatSerdeProperty(Property):
2163    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2167class QueryTransform(Expression):
2168    arg_types = {
2169        "expressions": True,
2170        "command_script": True,
2171        "schema": False,
2172        "row_format_before": False,
2173        "record_writer": False,
2174        "row_format_after": False,
2175        "record_reader": False,
2176    }
arg_types = {'expressions': True, 'command_script': True, 'schema': False, 'row_format_before': False, 'record_writer': False, 'row_format_after': False, 'record_reader': False}
key = 'querytransform'
class SampleProperty(Property):
2179class SampleProperty(Property):
2180    arg_types = {"this": True}
arg_types = {'this': True}
key = 'sampleproperty'
class SchemaCommentProperty(Property):
2183class SchemaCommentProperty(Property):
2184    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2187class SerdeProperties(Property):
2188    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2191class SetProperty(Property):
2192    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2195class SettingsProperty(Property):
2196    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2199class SortKeyProperty(Property):
2200    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2203class SqlSecurityProperty(Property):
2204    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2207class StabilityProperty(Property):
2208    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2211class TemporaryProperty(Property):
2212    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2215class TransientProperty(Property):
2216    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2219class VolatileProperty(Property):
2220    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2223class WithDataProperty(Property):
2224    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2227class WithJournalTableProperty(Property):
2228    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2231class Properties(Expression):
2232    arg_types = {"expressions": True}
2233
2234    NAME_TO_PROPERTY = {
2235        "ALGORITHM": AlgorithmProperty,
2236        "AUTO_INCREMENT": AutoIncrementProperty,
2237        "CHARACTER SET": CharacterSetProperty,
2238        "CLUSTERED_BY": ClusteredByProperty,
2239        "COLLATE": CollateProperty,
2240        "COMMENT": SchemaCommentProperty,
2241        "DEFINER": DefinerProperty,
2242        "DISTKEY": DistKeyProperty,
2243        "DISTSTYLE": DistStyleProperty,
2244        "ENGINE": EngineProperty,
2245        "EXECUTE AS": ExecuteAsProperty,
2246        "FORMAT": FileFormatProperty,
2247        "LANGUAGE": LanguageProperty,
2248        "LOCATION": LocationProperty,
2249        "PARTITIONED_BY": PartitionedByProperty,
2250        "RETURNS": ReturnsProperty,
2251        "ROW_FORMAT": RowFormatProperty,
2252        "SORTKEY": SortKeyProperty,
2253    }
2254
2255    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2256
2257    # CREATE property locations
2258    # Form: schema specified
2259    #   create [POST_CREATE]
2260    #     table a [POST_NAME]
2261    #     (b int) [POST_SCHEMA]
2262    #     with ([POST_WITH])
2263    #     index (b) [POST_INDEX]
2264    #
2265    # Form: alias selection
2266    #   create [POST_CREATE]
2267    #     table a [POST_NAME]
2268    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2269    #     index (c) [POST_INDEX]
2270    class Location(AutoName):
2271        POST_CREATE = auto()
2272        POST_NAME = auto()
2273        POST_SCHEMA = auto()
2274        POST_WITH = auto()
2275        POST_ALIAS = auto()
2276        POST_EXPRESSION = auto()
2277        POST_INDEX = auto()
2278        UNSUPPORTED = auto()
2279
2280    @classmethod
2281    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2282        expressions = []
2283        for key, value in properties_dict.items():
2284            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2285            if property_cls:
2286                expressions.append(property_cls(this=convert(value)))
2287            else:
2288                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2289
2290        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'AutoIncrementProperty'>, 'CHARACTER SET': <class 'CharacterSetProperty'>, 'CLUSTERED_BY': <class 'ClusteredByProperty'>, 'COLLATE': <class 'CollateProperty'>, 'COMMENT': <class 'SchemaCommentProperty'>, 'DEFINER': <class 'DefinerProperty'>, 'DISTKEY': <class 'DistKeyProperty'>, 'DISTSTYLE': <class 'DistStyleProperty'>, 'ENGINE': <class 'EngineProperty'>, 'EXECUTE AS': <class 'ExecuteAsProperty'>, 'FORMAT': <class 'FileFormatProperty'>, 'LANGUAGE': <class 'LanguageProperty'>, 'LOCATION': <class 'LocationProperty'>, 'PARTITIONED_BY': <class 'PartitionedByProperty'>, 'RETURNS': <class 'ReturnsProperty'>, 'ROW_FORMAT': <class 'RowFormatProperty'>, 'SORTKEY': <class 'SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'AlgorithmProperty'>: 'ALGORITHM', <class 'AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'CharacterSetProperty'>: 'CHARACTER SET', <class 'ClusteredByProperty'>: 'CLUSTERED_BY', <class 'CollateProperty'>: 'COLLATE', <class 'SchemaCommentProperty'>: 'COMMENT', <class 'DefinerProperty'>: 'DEFINER', <class 'DistKeyProperty'>: 'DISTKEY', <class 'DistStyleProperty'>: 'DISTSTYLE', <class 'EngineProperty'>: 'ENGINE', <class 'ExecuteAsProperty'>: 'EXECUTE AS', <class 'FileFormatProperty'>: 'FORMAT', <class 'LanguageProperty'>: 'LANGUAGE', <class 'LocationProperty'>: 'LOCATION', <class 'PartitionedByProperty'>: 'PARTITIONED_BY', <class 'ReturnsProperty'>: 'RETURNS', <class 'RowFormatProperty'>: 'ROW_FORMAT', <class 'SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> Properties:
2280    @classmethod
2281    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2282        expressions = []
2283        for key, value in properties_dict.items():
2284            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2285            if property_cls:
2286                expressions.append(property_cls(this=convert(value)))
2287            else:
2288                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2289
2290        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2270    class Location(AutoName):
2271        POST_CREATE = auto()
2272        POST_NAME = auto()
2273        POST_SCHEMA = auto()
2274        POST_WITH = auto()
2275        POST_ALIAS = auto()
2276        POST_EXPRESSION = auto()
2277        POST_INDEX = auto()
2278        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
2293class Qualify(Expression):
2294    pass
key = 'qualify'
class Return(Expression):
2298class Return(Expression):
2299    pass
key = 'return'
class Reference(Expression):
2302class Reference(Expression):
2303    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2306class Tuple(Expression):
2307    arg_types = {"expressions": False}
2308
2309    def isin(
2310        self,
2311        *expressions: t.Any,
2312        query: t.Optional[ExpOrStr] = None,
2313        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2314        copy: bool = True,
2315        **opts,
2316    ) -> In:
2317        return In(
2318            this=maybe_copy(self, copy),
2319            expressions=[convert(e, copy=copy) for e in expressions],
2320            query=maybe_parse(query, copy=copy, **opts) if query else None,
2321            unnest=Unnest(
2322                expressions=[
2323                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2324                ]
2325            )
2326            if unnest
2327            else None,
2328        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, Expression, NoneType] = None, unnest: Union[str, Expression, NoneType, Collection[Union[str, Expression]]] = None, copy: bool = True, **opts) -> In:
2309    def isin(
2310        self,
2311        *expressions: t.Any,
2312        query: t.Optional[ExpOrStr] = None,
2313        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2314        copy: bool = True,
2315        **opts,
2316    ) -> In:
2317        return In(
2318            this=maybe_copy(self, copy),
2319            expressions=[convert(e, copy=copy) for e in expressions],
2320            query=maybe_parse(query, copy=copy, **opts) if query else None,
2321            unnest=Unnest(
2322                expressions=[
2323                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2324                ]
2325            )
2326            if unnest
2327            else None,
2328        )
key = 'tuple'
class Subqueryable(Unionable):
2331class Subqueryable(Unionable):
2332    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2333        """
2334        Convert this expression to an aliased expression that can be used as a Subquery.
2335
2336        Example:
2337            >>> subquery = Select().select("x").from_("tbl").subquery()
2338            >>> Select().select("x").from_(subquery).sql()
2339            'SELECT x FROM (SELECT x FROM tbl)'
2340
2341        Args:
2342            alias (str | Identifier): an optional alias for the subquery
2343            copy (bool): if `False`, modify this expression instance in-place.
2344
2345        Returns:
2346            Alias: the subquery
2347        """
2348        instance = maybe_copy(self, copy)
2349        if not isinstance(alias, Expression):
2350            alias = TableAlias(this=to_identifier(alias)) if alias else None
2351
2352        return Subquery(this=instance, alias=alias)
2353
2354    def limit(
2355        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2356    ) -> Select:
2357        raise NotImplementedError
2358
2359    @property
2360    def ctes(self):
2361        with_ = self.args.get("with")
2362        if not with_:
2363            return []
2364        return with_.expressions
2365
2366    @property
2367    def selects(self) -> t.List[Expression]:
2368        raise NotImplementedError("Subqueryable objects must implement `selects`")
2369
2370    @property
2371    def named_selects(self) -> t.List[str]:
2372        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2373
2374    def select(
2375        self,
2376        *expressions: t.Optional[ExpOrStr],
2377        append: bool = True,
2378        dialect: DialectType = None,
2379        copy: bool = True,
2380        **opts,
2381    ) -> Subqueryable:
2382        raise NotImplementedError("Subqueryable objects must implement `select`")
2383
2384    def with_(
2385        self,
2386        alias: ExpOrStr,
2387        as_: ExpOrStr,
2388        recursive: t.Optional[bool] = None,
2389        append: bool = True,
2390        dialect: DialectType = None,
2391        copy: bool = True,
2392        **opts,
2393    ) -> Subqueryable:
2394        """
2395        Append to or set the common table expressions.
2396
2397        Example:
2398            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2399            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2400
2401        Args:
2402            alias: the SQL code string to parse as the table name.
2403                If an `Expression` instance is passed, this is used as-is.
2404            as_: the SQL code string to parse as the table expression.
2405                If an `Expression` instance is passed, it will be used as-is.
2406            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2407            append: if `True`, add to any existing expressions.
2408                Otherwise, this resets the expressions.
2409            dialect: the dialect used to parse the input expression.
2410            copy: if `False`, modify this expression instance in-place.
2411            opts: other options to use to parse the input expressions.
2412
2413        Returns:
2414            The modified expression.
2415        """
2416        return _apply_cte_builder(
2417            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2418        )
def subquery( self, alias: Union[str, Expression, NoneType] = None, copy: bool = True) -> Subquery:
2332    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2333        """
2334        Convert this expression to an aliased expression that can be used as a Subquery.
2335
2336        Example:
2337            >>> subquery = Select().select("x").from_("tbl").subquery()
2338            >>> Select().select("x").from_(subquery).sql()
2339            'SELECT x FROM (SELECT x FROM tbl)'
2340
2341        Args:
2342            alias (str | Identifier): an optional alias for the subquery
2343            copy (bool): if `False`, modify this expression instance in-place.
2344
2345        Returns:
2346            Alias: the subquery
2347        """
2348        instance = maybe_copy(self, copy)
2349        if not isinstance(alias, Expression):
2350            alias = TableAlias(this=to_identifier(alias)) if alias else None
2351
2352        return Subquery(this=instance, alias=alias)

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression: Union[str, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2354    def limit(
2355        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2356    ) -> Select:
2357        raise NotImplementedError
ctes
selects: List[Expression]
named_selects: List[str]
def select( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Subqueryable:
2374    def select(
2375        self,
2376        *expressions: t.Optional[ExpOrStr],
2377        append: bool = True,
2378        dialect: DialectType = None,
2379        copy: bool = True,
2380        **opts,
2381    ) -> Subqueryable:
2382        raise NotImplementedError("Subqueryable objects must implement `select`")
def with_( self, alias: Union[str, Expression], as_: Union[str, Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Subqueryable:
2384    def with_(
2385        self,
2386        alias: ExpOrStr,
2387        as_: ExpOrStr,
2388        recursive: t.Optional[bool] = None,
2389        append: bool = True,
2390        dialect: DialectType = None,
2391        copy: bool = True,
2392        **opts,
2393    ) -> Subqueryable:
2394        """
2395        Append to or set the common table expressions.
2396
2397        Example:
2398            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2399            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2400
2401        Args:
2402            alias: the SQL code string to parse as the table name.
2403                If an `Expression` instance is passed, this is used as-is.
2404            as_: the SQL code string to parse as the table expression.
2405                If an `Expression` instance is passed, it will be used as-is.
2406            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2407            append: if `True`, add to any existing expressions.
2408                Otherwise, this resets the expressions.
2409            dialect: the dialect used to parse the input expression.
2410            copy: if `False`, modify this expression instance in-place.
2411            opts: other options to use to parse the input expressions.
2412
2413        Returns:
2414            The modified expression.
2415        """
2416        return _apply_cte_builder(
2417            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2418        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'subqueryable'
QUERY_MODIFIERS = {'match': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
class WithTableHint(Expression):
2446class WithTableHint(Expression):
2447    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2451class IndexTableHint(Expression):
2452    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2455class Table(Expression):
2456    arg_types = {
2457        "this": True,
2458        "alias": False,
2459        "db": False,
2460        "catalog": False,
2461        "laterals": False,
2462        "joins": False,
2463        "pivots": False,
2464        "hints": False,
2465        "system_time": False,
2466        "version": False,
2467        "format": False,
2468        "pattern": False,
2469        "index": False,
2470    }
2471
2472    @property
2473    def name(self) -> str:
2474        if isinstance(self.this, Func):
2475            return ""
2476        return self.this.name
2477
2478    @property
2479    def db(self) -> str:
2480        return self.text("db")
2481
2482    @property
2483    def catalog(self) -> str:
2484        return self.text("catalog")
2485
2486    @property
2487    def selects(self) -> t.List[Expression]:
2488        return []
2489
2490    @property
2491    def named_selects(self) -> t.List[str]:
2492        return []
2493
2494    @property
2495    def parts(self) -> t.List[Expression]:
2496        """Return the parts of a table in order catalog, db, table."""
2497        parts: t.List[Expression] = []
2498
2499        for arg in ("catalog", "db", "this"):
2500            part = self.args.get(arg)
2501
2502            if isinstance(part, Dot):
2503                parts.extend(part.flatten())
2504            elif isinstance(part, Expression):
2505                parts.append(part)
2506
2507        return parts
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False, 'version': False, 'format': False, 'pattern': False, 'index': False}
name: str
db: str
catalog: str
selects: List[Expression]
named_selects: List[str]
parts: List[Expression]

Return the parts of a table in order catalog, db, table.

key = 'table'
class Union(Subqueryable):
2510class Union(Subqueryable):
2511    arg_types = {
2512        "with": False,
2513        "this": True,
2514        "expression": True,
2515        "distinct": False,
2516        "by_name": False,
2517        **QUERY_MODIFIERS,
2518    }
2519
2520    def limit(
2521        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2522    ) -> Select:
2523        """
2524        Set the LIMIT expression.
2525
2526        Example:
2527            >>> select("1").union(select("1")).limit(1).sql()
2528            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2529
2530        Args:
2531            expression: the SQL code string to parse.
2532                This can also be an integer.
2533                If a `Limit` instance is passed, this is used as-is.
2534                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2535            dialect: the dialect used to parse the input expression.
2536            copy: if `False`, modify this expression instance in-place.
2537            opts: other options to use to parse the input expressions.
2538
2539        Returns:
2540            The limited subqueryable.
2541        """
2542        return (
2543            select("*")
2544            .from_(self.subquery(alias="_l_0", copy=copy))
2545            .limit(expression, dialect=dialect, copy=False, **opts)
2546        )
2547
2548    def select(
2549        self,
2550        *expressions: t.Optional[ExpOrStr],
2551        append: bool = True,
2552        dialect: DialectType = None,
2553        copy: bool = True,
2554        **opts,
2555    ) -> Union:
2556        """Append to or set the SELECT of the union recursively.
2557
2558        Example:
2559            >>> from sqlglot import parse_one
2560            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2561            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2562
2563        Args:
2564            *expressions: the SQL code strings to parse.
2565                If an `Expression` instance is passed, it will be used as-is.
2566            append: if `True`, add to any existing expressions.
2567                Otherwise, this resets the expressions.
2568            dialect: the dialect used to parse the input expressions.
2569            copy: if `False`, modify this expression instance in-place.
2570            opts: other options to use to parse the input expressions.
2571
2572        Returns:
2573            Union: the modified expression.
2574        """
2575        this = self.copy() if copy else self
2576        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2577        this.expression.unnest().select(
2578            *expressions, append=append, dialect=dialect, copy=False, **opts
2579        )
2580        return this
2581
2582    @property
2583    def named_selects(self) -> t.List[str]:
2584        return self.this.unnest().named_selects
2585
2586    @property
2587    def is_star(self) -> bool:
2588        return self.this.is_star or self.expression.is_star
2589
2590    @property
2591    def selects(self) -> t.List[Expression]:
2592        return self.this.unnest().selects
2593
2594    @property
2595    def left(self):
2596        return self.this
2597
2598    @property
2599    def right(self):
2600        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'by_name': False, 'match': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def limit( self, expression: Union[str, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2520    def limit(
2521        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2522    ) -> Select:
2523        """
2524        Set the LIMIT expression.
2525
2526        Example:
2527            >>> select("1").union(select("1")).limit(1).sql()
2528            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2529
2530        Args:
2531            expression: the SQL code string to parse.
2532                This can also be an integer.
2533                If a `Limit` instance is passed, this is used as-is.
2534                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2535            dialect: the dialect used to parse the input expression.
2536            copy: if `False`, modify this expression instance in-place.
2537            opts: other options to use to parse the input expressions.
2538
2539        Returns:
2540            The limited subqueryable.
2541        """
2542        return (
2543            select("*")
2544            .from_(self.subquery(alias="_l_0", copy=copy))
2545            .limit(expression, dialect=dialect, copy=False, **opts)
2546        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The limited subqueryable.

def select( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Union:
2548    def select(
2549        self,
2550        *expressions: t.Optional[ExpOrStr],
2551        append: bool = True,
2552        dialect: DialectType = None,
2553        copy: bool = True,
2554        **opts,
2555    ) -> Union:
2556        """Append to or set the SELECT of the union recursively.
2557
2558        Example:
2559            >>> from sqlglot import parse_one
2560            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2561            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2562
2563        Args:
2564            *expressions: the SQL code strings to parse.
2565                If an `Expression` instance is passed, it will be used as-is.
2566            append: if `True`, add to any existing expressions.
2567                Otherwise, this resets the expressions.
2568            dialect: the dialect used to parse the input expressions.
2569            copy: if `False`, modify this expression instance in-place.
2570            opts: other options to use to parse the input expressions.
2571
2572        Returns:
2573            Union: the modified expression.
2574        """
2575        this = self.copy() if copy else self
2576        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2577        this.expression.unnest().select(
2578            *expressions, append=append, dialect=dialect, copy=False, **opts
2579        )
2580        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

selects: List[Expression]
left
right
key = 'union'
class Except(Union):
2603class Except(Union):
2604    pass
key = 'except'
class Intersect(Union):
2607class Intersect(Union):
2608    pass
key = 'intersect'
class Unnest(UDTF):
2611class Unnest(UDTF):
2612    arg_types = {
2613        "expressions": True,
2614        "alias": False,
2615        "offset": False,
2616    }
arg_types = {'expressions': True, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
2619class Update(Expression):
2620    arg_types = {
2621        "with": False,
2622        "this": False,
2623        "expressions": True,
2624        "from": False,
2625        "where": False,
2626        "returning": False,
2627        "order": False,
2628        "limit": False,
2629    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'order': False, 'limit': False}
key = 'update'
class Values(UDTF):
2632class Values(UDTF):
2633    arg_types = {
2634        "expressions": True,
2635        "ordinality": False,
2636        "alias": False,
2637    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2640class Var(Expression):
2641    pass
key = 'var'
class Version(Expression):
2644class Version(Expression):
2645    """
2646    Time travel, iceberg, bigquery etc
2647    https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots
2648    https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html
2649    https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
2650    https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16
2651    this is either TIMESTAMP or VERSION
2652    kind is ("AS OF", "BETWEEN")
2653    """
2654
2655    arg_types = {"this": True, "kind": True, "expression": False}
arg_types = {'this': True, 'kind': True, 'expression': False}
key = 'version'
class Schema(Expression):
2658class Schema(Expression):
2659    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2664class Lock(Expression):
2665    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
2668class Select(Subqueryable):
2669    arg_types = {
2670        "with": False,
2671        "kind": False,
2672        "expressions": False,
2673        "hint": False,
2674        "distinct": False,
2675        "into": False,
2676        "from": False,
2677        **QUERY_MODIFIERS,
2678    }
2679
2680    def from_(
2681        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2682    ) -> Select:
2683        """
2684        Set the FROM expression.
2685
2686        Example:
2687            >>> Select().from_("tbl").select("x").sql()
2688            'SELECT x FROM tbl'
2689
2690        Args:
2691            expression : the SQL code strings to parse.
2692                If a `From` instance is passed, this is used as-is.
2693                If another `Expression` instance is passed, it will be wrapped in a `From`.
2694            dialect: the dialect used to parse the input expression.
2695            copy: if `False`, modify this expression instance in-place.
2696            opts: other options to use to parse the input expressions.
2697
2698        Returns:
2699            The modified Select expression.
2700        """
2701        return _apply_builder(
2702            expression=expression,
2703            instance=self,
2704            arg="from",
2705            into=From,
2706            prefix="FROM",
2707            dialect=dialect,
2708            copy=copy,
2709            **opts,
2710        )
2711
2712    def group_by(
2713        self,
2714        *expressions: t.Optional[ExpOrStr],
2715        append: bool = True,
2716        dialect: DialectType = None,
2717        copy: bool = True,
2718        **opts,
2719    ) -> Select:
2720        """
2721        Set the GROUP BY expression.
2722
2723        Example:
2724            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2725            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2726
2727        Args:
2728            *expressions: the SQL code strings to parse.
2729                If a `Group` instance is passed, this is used as-is.
2730                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2731                If nothing is passed in then a group by is not applied to the expression
2732            append: if `True`, add to any existing expressions.
2733                Otherwise, this flattens all the `Group` expression into a single expression.
2734            dialect: the dialect used to parse the input expression.
2735            copy: if `False`, modify this expression instance in-place.
2736            opts: other options to use to parse the input expressions.
2737
2738        Returns:
2739            The modified Select expression.
2740        """
2741        if not expressions:
2742            return self if not copy else self.copy()
2743
2744        return _apply_child_list_builder(
2745            *expressions,
2746            instance=self,
2747            arg="group",
2748            append=append,
2749            copy=copy,
2750            prefix="GROUP BY",
2751            into=Group,
2752            dialect=dialect,
2753            **opts,
2754        )
2755
2756    def order_by(
2757        self,
2758        *expressions: t.Optional[ExpOrStr],
2759        append: bool = True,
2760        dialect: DialectType = None,
2761        copy: bool = True,
2762        **opts,
2763    ) -> Select:
2764        """
2765        Set the ORDER BY expression.
2766
2767        Example:
2768            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2769            'SELECT x FROM tbl ORDER BY x DESC'
2770
2771        Args:
2772            *expressions: the SQL code strings to parse.
2773                If a `Group` instance is passed, this is used as-is.
2774                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2775            append: if `True`, add to any existing expressions.
2776                Otherwise, this flattens all the `Order` expression into a single expression.
2777            dialect: the dialect used to parse the input expression.
2778            copy: if `False`, modify this expression instance in-place.
2779            opts: other options to use to parse the input expressions.
2780
2781        Returns:
2782            The modified Select expression.
2783        """
2784        return _apply_child_list_builder(
2785            *expressions,
2786            instance=self,
2787            arg="order",
2788            append=append,
2789            copy=copy,
2790            prefix="ORDER BY",
2791            into=Order,
2792            dialect=dialect,
2793            **opts,
2794        )
2795
2796    def sort_by(
2797        self,
2798        *expressions: t.Optional[ExpOrStr],
2799        append: bool = True,
2800        dialect: DialectType = None,
2801        copy: bool = True,
2802        **opts,
2803    ) -> Select:
2804        """
2805        Set the SORT BY expression.
2806
2807        Example:
2808            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2809            'SELECT x FROM tbl SORT BY x DESC'
2810
2811        Args:
2812            *expressions: the SQL code strings to parse.
2813                If a `Group` instance is passed, this is used as-is.
2814                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2815            append: if `True`, add to any existing expressions.
2816                Otherwise, this flattens all the `Order` expression into a single expression.
2817            dialect: the dialect used to parse the input expression.
2818            copy: if `False`, modify this expression instance in-place.
2819            opts: other options to use to parse the input expressions.
2820
2821        Returns:
2822            The modified Select expression.
2823        """
2824        return _apply_child_list_builder(
2825            *expressions,
2826            instance=self,
2827            arg="sort",
2828            append=append,
2829            copy=copy,
2830            prefix="SORT BY",
2831            into=Sort,
2832            dialect=dialect,
2833            **opts,
2834        )
2835
2836    def cluster_by(
2837        self,
2838        *expressions: t.Optional[ExpOrStr],
2839        append: bool = True,
2840        dialect: DialectType = None,
2841        copy: bool = True,
2842        **opts,
2843    ) -> Select:
2844        """
2845        Set the CLUSTER BY expression.
2846
2847        Example:
2848            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2849            'SELECT x FROM tbl CLUSTER BY x DESC'
2850
2851        Args:
2852            *expressions: the SQL code strings to parse.
2853                If a `Group` instance is passed, this is used as-is.
2854                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2855            append: if `True`, add to any existing expressions.
2856                Otherwise, this flattens all the `Order` expression into a single expression.
2857            dialect: the dialect used to parse the input expression.
2858            copy: if `False`, modify this expression instance in-place.
2859            opts: other options to use to parse the input expressions.
2860
2861        Returns:
2862            The modified Select expression.
2863        """
2864        return _apply_child_list_builder(
2865            *expressions,
2866            instance=self,
2867            arg="cluster",
2868            append=append,
2869            copy=copy,
2870            prefix="CLUSTER BY",
2871            into=Cluster,
2872            dialect=dialect,
2873            **opts,
2874        )
2875
2876    def limit(
2877        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2878    ) -> Select:
2879        """
2880        Set the LIMIT expression.
2881
2882        Example:
2883            >>> Select().from_("tbl").select("x").limit(10).sql()
2884            'SELECT x FROM tbl LIMIT 10'
2885
2886        Args:
2887            expression: the SQL code string to parse.
2888                This can also be an integer.
2889                If a `Limit` instance is passed, this is used as-is.
2890                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2891            dialect: the dialect used to parse the input expression.
2892            copy: if `False`, modify this expression instance in-place.
2893            opts: other options to use to parse the input expressions.
2894
2895        Returns:
2896            Select: the modified expression.
2897        """
2898        return _apply_builder(
2899            expression=expression,
2900            instance=self,
2901            arg="limit",
2902            into=Limit,
2903            prefix="LIMIT",
2904            dialect=dialect,
2905            copy=copy,
2906            into_arg="expression",
2907            **opts,
2908        )
2909
2910    def offset(
2911        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2912    ) -> Select:
2913        """
2914        Set the OFFSET expression.
2915
2916        Example:
2917            >>> Select().from_("tbl").select("x").offset(10).sql()
2918            'SELECT x FROM tbl OFFSET 10'
2919
2920        Args:
2921            expression: the SQL code string to parse.
2922                This can also be an integer.
2923                If a `Offset` instance is passed, this is used as-is.
2924                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2925            dialect: the dialect used to parse the input expression.
2926            copy: if `False`, modify this expression instance in-place.
2927            opts: other options to use to parse the input expressions.
2928
2929        Returns:
2930            The modified Select expression.
2931        """
2932        return _apply_builder(
2933            expression=expression,
2934            instance=self,
2935            arg="offset",
2936            into=Offset,
2937            prefix="OFFSET",
2938            dialect=dialect,
2939            copy=copy,
2940            into_arg="expression",
2941            **opts,
2942        )
2943
2944    def select(
2945        self,
2946        *expressions: t.Optional[ExpOrStr],
2947        append: bool = True,
2948        dialect: DialectType = None,
2949        copy: bool = True,
2950        **opts,
2951    ) -> Select:
2952        """
2953        Append to or set the SELECT expressions.
2954
2955        Example:
2956            >>> Select().select("x", "y").sql()
2957            'SELECT x, y'
2958
2959        Args:
2960            *expressions: the SQL code strings to parse.
2961                If an `Expression` instance is passed, it will be used as-is.
2962            append: if `True`, add to any existing expressions.
2963                Otherwise, this resets the expressions.
2964            dialect: the dialect used to parse the input expressions.
2965            copy: if `False`, modify this expression instance in-place.
2966            opts: other options to use to parse the input expressions.
2967
2968        Returns:
2969            The modified Select expression.
2970        """
2971        return _apply_list_builder(
2972            *expressions,
2973            instance=self,
2974            arg="expressions",
2975            append=append,
2976            dialect=dialect,
2977            copy=copy,
2978            **opts,
2979        )
2980
2981    def lateral(
2982        self,
2983        *expressions: t.Optional[ExpOrStr],
2984        append: bool = True,
2985        dialect: DialectType = None,
2986        copy: bool = True,
2987        **opts,
2988    ) -> Select:
2989        """
2990        Append to or set the LATERAL expressions.
2991
2992        Example:
2993            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2994            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2995
2996        Args:
2997            *expressions: the SQL code strings to parse.
2998                If an `Expression` instance is passed, it will be used as-is.
2999            append: if `True`, add to any existing expressions.
3000                Otherwise, this resets the expressions.
3001            dialect: the dialect used to parse the input expressions.
3002            copy: if `False`, modify this expression instance in-place.
3003            opts: other options to use to parse the input expressions.
3004
3005        Returns:
3006            The modified Select expression.
3007        """
3008        return _apply_list_builder(
3009            *expressions,
3010            instance=self,
3011            arg="laterals",
3012            append=append,
3013            into=Lateral,
3014            prefix="LATERAL VIEW",
3015            dialect=dialect,
3016            copy=copy,
3017            **opts,
3018        )
3019
3020    def join(
3021        self,
3022        expression: ExpOrStr,
3023        on: t.Optional[ExpOrStr] = None,
3024        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
3025        append: bool = True,
3026        join_type: t.Optional[str] = None,
3027        join_alias: t.Optional[Identifier | str] = None,
3028        dialect: DialectType = None,
3029        copy: bool = True,
3030        **opts,
3031    ) -> Select:
3032        """
3033        Append to or set the JOIN expressions.
3034
3035        Example:
3036            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
3037            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
3038
3039            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
3040            'SELECT 1 FROM a JOIN b USING (x, y, z)'
3041
3042            Use `join_type` to change the type of join:
3043
3044            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
3045            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
3046
3047        Args:
3048            expression: the SQL code string to parse.
3049                If an `Expression` instance is passed, it will be used as-is.
3050            on: optionally specify the join "on" criteria as a SQL string.
3051                If an `Expression` instance is passed, it will be used as-is.
3052            using: optionally specify the join "using" criteria as a SQL string.
3053                If an `Expression` instance is passed, it will be used as-is.
3054            append: if `True`, add to any existing expressions.
3055                Otherwise, this resets the expressions.
3056            join_type: if set, alter the parsed join type.
3057            join_alias: an optional alias for the joined source.
3058            dialect: the dialect used to parse the input expressions.
3059            copy: if `False`, modify this expression instance in-place.
3060            opts: other options to use to parse the input expressions.
3061
3062        Returns:
3063            Select: the modified expression.
3064        """
3065        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3066
3067        try:
3068            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3069        except ParseError:
3070            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3071
3072        join = expression if isinstance(expression, Join) else Join(this=expression)
3073
3074        if isinstance(join.this, Select):
3075            join.this.replace(join.this.subquery())
3076
3077        if join_type:
3078            method: t.Optional[Token]
3079            side: t.Optional[Token]
3080            kind: t.Optional[Token]
3081
3082            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3083
3084            if method:
3085                join.set("method", method.text)
3086            if side:
3087                join.set("side", side.text)
3088            if kind:
3089                join.set("kind", kind.text)
3090
3091        if on:
3092            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3093            join.set("on", on)
3094
3095        if using:
3096            join = _apply_list_builder(
3097                *ensure_list(using),
3098                instance=join,
3099                arg="using",
3100                append=append,
3101                copy=copy,
3102                into=Identifier,
3103                **opts,
3104            )
3105
3106        if join_alias:
3107            join.set("this", alias_(join.this, join_alias, table=True))
3108
3109        return _apply_list_builder(
3110            join,
3111            instance=self,
3112            arg="joins",
3113            append=append,
3114            copy=copy,
3115            **opts,
3116        )
3117
3118    def where(
3119        self,
3120        *expressions: t.Optional[ExpOrStr],
3121        append: bool = True,
3122        dialect: DialectType = None,
3123        copy: bool = True,
3124        **opts,
3125    ) -> Select:
3126        """
3127        Append to or set the WHERE expressions.
3128
3129        Example:
3130            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3131            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3132
3133        Args:
3134            *expressions: the SQL code strings to parse.
3135                If an `Expression` instance is passed, it will be used as-is.
3136                Multiple expressions are combined with an AND operator.
3137            append: if `True`, AND the new expressions to any existing expression.
3138                Otherwise, this resets the expression.
3139            dialect: the dialect used to parse the input expressions.
3140            copy: if `False`, modify this expression instance in-place.
3141            opts: other options to use to parse the input expressions.
3142
3143        Returns:
3144            Select: the modified expression.
3145        """
3146        return _apply_conjunction_builder(
3147            *expressions,
3148            instance=self,
3149            arg="where",
3150            append=append,
3151            into=Where,
3152            dialect=dialect,
3153            copy=copy,
3154            **opts,
3155        )
3156
3157    def having(
3158        self,
3159        *expressions: t.Optional[ExpOrStr],
3160        append: bool = True,
3161        dialect: DialectType = None,
3162        copy: bool = True,
3163        **opts,
3164    ) -> Select:
3165        """
3166        Append to or set the HAVING expressions.
3167
3168        Example:
3169            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3170            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3171
3172        Args:
3173            *expressions: the SQL code strings to parse.
3174                If an `Expression` instance is passed, it will be used as-is.
3175                Multiple expressions are combined with an AND operator.
3176            append: if `True`, AND the new expressions to any existing expression.
3177                Otherwise, this resets the expression.
3178            dialect: the dialect used to parse the input expressions.
3179            copy: if `False`, modify this expression instance in-place.
3180            opts: other options to use to parse the input expressions.
3181
3182        Returns:
3183            The modified Select expression.
3184        """
3185        return _apply_conjunction_builder(
3186            *expressions,
3187            instance=self,
3188            arg="having",
3189            append=append,
3190            into=Having,
3191            dialect=dialect,
3192            copy=copy,
3193            **opts,
3194        )
3195
3196    def window(
3197        self,
3198        *expressions: t.Optional[ExpOrStr],
3199        append: bool = True,
3200        dialect: DialectType = None,
3201        copy: bool = True,
3202        **opts,
3203    ) -> Select:
3204        return _apply_list_builder(
3205            *expressions,
3206            instance=self,
3207            arg="windows",
3208            append=append,
3209            into=Window,
3210            dialect=dialect,
3211            copy=copy,
3212            **opts,
3213        )
3214
3215    def qualify(
3216        self,
3217        *expressions: t.Optional[ExpOrStr],
3218        append: bool = True,
3219        dialect: DialectType = None,
3220        copy: bool = True,
3221        **opts,
3222    ) -> Select:
3223        return _apply_conjunction_builder(
3224            *expressions,
3225            instance=self,
3226            arg="qualify",
3227            append=append,
3228            into=Qualify,
3229            dialect=dialect,
3230            copy=copy,
3231            **opts,
3232        )
3233
3234    def distinct(
3235        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3236    ) -> Select:
3237        """
3238        Set the OFFSET expression.
3239
3240        Example:
3241            >>> Select().from_("tbl").select("x").distinct().sql()
3242            'SELECT DISTINCT x FROM tbl'
3243
3244        Args:
3245            ons: the expressions to distinct on
3246            distinct: whether the Select should be distinct
3247            copy: if `False`, modify this expression instance in-place.
3248
3249        Returns:
3250            Select: the modified expression.
3251        """
3252        instance = maybe_copy(self, copy)
3253        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3254        instance.set("distinct", Distinct(on=on) if distinct else None)
3255        return instance
3256
3257    def ctas(
3258        self,
3259        table: ExpOrStr,
3260        properties: t.Optional[t.Dict] = None,
3261        dialect: DialectType = None,
3262        copy: bool = True,
3263        **opts,
3264    ) -> Create:
3265        """
3266        Convert this expression to a CREATE TABLE AS statement.
3267
3268        Example:
3269            >>> Select().select("*").from_("tbl").ctas("x").sql()
3270            'CREATE TABLE x AS SELECT * FROM tbl'
3271
3272        Args:
3273            table: the SQL code string to parse as the table name.
3274                If another `Expression` instance is passed, it will be used as-is.
3275            properties: an optional mapping of table properties
3276            dialect: the dialect used to parse the input table.
3277            copy: if `False`, modify this expression instance in-place.
3278            opts: other options to use to parse the input table.
3279
3280        Returns:
3281            The new Create expression.
3282        """
3283        instance = maybe_copy(self, copy)
3284        table_expression = maybe_parse(
3285            table,
3286            into=Table,
3287            dialect=dialect,
3288            **opts,
3289        )
3290        properties_expression = None
3291        if properties:
3292            properties_expression = Properties.from_dict(properties)
3293
3294        return Create(
3295            this=table_expression,
3296            kind="table",
3297            expression=instance,
3298            properties=properties_expression,
3299        )
3300
3301    def lock(self, update: bool = True, copy: bool = True) -> Select:
3302        """
3303        Set the locking read mode for this expression.
3304
3305        Examples:
3306            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3307            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3308
3309            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3310            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3311
3312        Args:
3313            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3314            copy: if `False`, modify this expression instance in-place.
3315
3316        Returns:
3317            The modified expression.
3318        """
3319        inst = maybe_copy(self, copy)
3320        inst.set("locks", [Lock(update=update)])
3321
3322        return inst
3323
3324    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3325        """
3326        Set hints for this expression.
3327
3328        Examples:
3329            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3330            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3331
3332        Args:
3333            hints: The SQL code strings to parse as the hints.
3334                If an `Expression` instance is passed, it will be used as-is.
3335            dialect: The dialect used to parse the hints.
3336            copy: If `False`, modify this expression instance in-place.
3337
3338        Returns:
3339            The modified expression.
3340        """
3341        inst = maybe_copy(self, copy)
3342        inst.set(
3343            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3344        )
3345
3346        return inst
3347
3348    @property
3349    def named_selects(self) -> t.List[str]:
3350        return [e.output_name for e in self.expressions if e.alias_or_name]
3351
3352    @property
3353    def is_star(self) -> bool:
3354        return any(expression.is_star for expression in self.expressions)
3355
3356    @property
3357    def selects(self) -> t.List[Expression]:
3358        return self.expressions
arg_types = {'with': False, 'kind': False, 'expressions': False, 'hint': False, 'distinct': False, 'into': False, 'from': False, 'match': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def from_( self, expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2680    def from_(
2681        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2682    ) -> Select:
2683        """
2684        Set the FROM expression.
2685
2686        Example:
2687            >>> Select().from_("tbl").select("x").sql()
2688            'SELECT x FROM tbl'
2689
2690        Args:
2691            expression : the SQL code strings to parse.
2692                If a `From` instance is passed, this is used as-is.
2693                If another `Expression` instance is passed, it will be wrapped in a `From`.
2694            dialect: the dialect used to parse the input expression.
2695            copy: if `False`, modify this expression instance in-place.
2696            opts: other options to use to parse the input expressions.
2697
2698        Returns:
2699            The modified Select expression.
2700        """
2701        return _apply_builder(
2702            expression=expression,
2703            instance=self,
2704            arg="from",
2705            into=From,
2706            prefix="FROM",
2707            dialect=dialect,
2708            copy=copy,
2709            **opts,
2710        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def group_by( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2712    def group_by(
2713        self,
2714        *expressions: t.Optional[ExpOrStr],
2715        append: bool = True,
2716        dialect: DialectType = None,
2717        copy: bool = True,
2718        **opts,
2719    ) -> Select:
2720        """
2721        Set the GROUP BY expression.
2722
2723        Example:
2724            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2725            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2726
2727        Args:
2728            *expressions: the SQL code strings to parse.
2729                If a `Group` instance is passed, this is used as-is.
2730                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2731                If nothing is passed in then a group by is not applied to the expression
2732            append: if `True`, add to any existing expressions.
2733                Otherwise, this flattens all the `Group` expression into a single expression.
2734            dialect: the dialect used to parse the input expression.
2735            copy: if `False`, modify this expression instance in-place.
2736            opts: other options to use to parse the input expressions.
2737
2738        Returns:
2739            The modified Select expression.
2740        """
2741        if not expressions:
2742            return self if not copy else self.copy()
2743
2744        return _apply_child_list_builder(
2745            *expressions,
2746            instance=self,
2747            arg="group",
2748            append=append,
2749            copy=copy,
2750            prefix="GROUP BY",
2751            into=Group,
2752            dialect=dialect,
2753            **opts,
2754        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def order_by( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2756    def order_by(
2757        self,
2758        *expressions: t.Optional[ExpOrStr],
2759        append: bool = True,
2760        dialect: DialectType = None,
2761        copy: bool = True,
2762        **opts,
2763    ) -> Select:
2764        """
2765        Set the ORDER BY expression.
2766
2767        Example:
2768            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2769            'SELECT x FROM tbl ORDER BY x DESC'
2770
2771        Args:
2772            *expressions: the SQL code strings to parse.
2773                If a `Group` instance is passed, this is used as-is.
2774                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2775            append: if `True`, add to any existing expressions.
2776                Otherwise, this flattens all the `Order` expression into a single expression.
2777            dialect: the dialect used to parse the input expression.
2778            copy: if `False`, modify this expression instance in-place.
2779            opts: other options to use to parse the input expressions.
2780
2781        Returns:
2782            The modified Select expression.
2783        """
2784        return _apply_child_list_builder(
2785            *expressions,
2786            instance=self,
2787            arg="order",
2788            append=append,
2789            copy=copy,
2790            prefix="ORDER BY",
2791            into=Order,
2792            dialect=dialect,
2793            **opts,
2794        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def sort_by( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2796    def sort_by(
2797        self,
2798        *expressions: t.Optional[ExpOrStr],
2799        append: bool = True,
2800        dialect: DialectType = None,
2801        copy: bool = True,
2802        **opts,
2803    ) -> Select:
2804        """
2805        Set the SORT BY expression.
2806
2807        Example:
2808            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2809            'SELECT x FROM tbl SORT BY x DESC'
2810
2811        Args:
2812            *expressions: the SQL code strings to parse.
2813                If a `Group` instance is passed, this is used as-is.
2814                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2815            append: if `True`, add to any existing expressions.
2816                Otherwise, this flattens all the `Order` expression into a single expression.
2817            dialect: the dialect used to parse the input expression.
2818            copy: if `False`, modify this expression instance in-place.
2819            opts: other options to use to parse the input expressions.
2820
2821        Returns:
2822            The modified Select expression.
2823        """
2824        return _apply_child_list_builder(
2825            *expressions,
2826            instance=self,
2827            arg="sort",
2828            append=append,
2829            copy=copy,
2830            prefix="SORT BY",
2831            into=Sort,
2832            dialect=dialect,
2833            **opts,
2834        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def cluster_by( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2836    def cluster_by(
2837        self,
2838        *expressions: t.Optional[ExpOrStr],
2839        append: bool = True,
2840        dialect: DialectType = None,
2841        copy: bool = True,
2842        **opts,
2843    ) -> Select:
2844        """
2845        Set the CLUSTER BY expression.
2846
2847        Example:
2848            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2849            'SELECT x FROM tbl CLUSTER BY x DESC'
2850
2851        Args:
2852            *expressions: the SQL code strings to parse.
2853                If a `Group` instance is passed, this is used as-is.
2854                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2855            append: if `True`, add to any existing expressions.
2856                Otherwise, this flattens all the `Order` expression into a single expression.
2857            dialect: the dialect used to parse the input expression.
2858            copy: if `False`, modify this expression instance in-place.
2859            opts: other options to use to parse the input expressions.
2860
2861        Returns:
2862            The modified Select expression.
2863        """
2864        return _apply_child_list_builder(
2865            *expressions,
2866            instance=self,
2867            arg="cluster",
2868            append=append,
2869            copy=copy,
2870            prefix="CLUSTER BY",
2871            into=Cluster,
2872            dialect=dialect,
2873            **opts,
2874        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def limit( self, expression: Union[str, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2876    def limit(
2877        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2878    ) -> Select:
2879        """
2880        Set the LIMIT expression.
2881
2882        Example:
2883            >>> Select().from_("tbl").select("x").limit(10).sql()
2884            'SELECT x FROM tbl LIMIT 10'
2885
2886        Args:
2887            expression: the SQL code string to parse.
2888                This can also be an integer.
2889                If a `Limit` instance is passed, this is used as-is.
2890                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2891            dialect: the dialect used to parse the input expression.
2892            copy: if `False`, modify this expression instance in-place.
2893            opts: other options to use to parse the input expressions.
2894
2895        Returns:
2896            Select: the modified expression.
2897        """
2898        return _apply_builder(
2899            expression=expression,
2900            instance=self,
2901            arg="limit",
2902            into=Limit,
2903            prefix="LIMIT",
2904            dialect=dialect,
2905            copy=copy,
2906            into_arg="expression",
2907            **opts,
2908        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression: Union[str, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2910    def offset(
2911        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2912    ) -> Select:
2913        """
2914        Set the OFFSET expression.
2915
2916        Example:
2917            >>> Select().from_("tbl").select("x").offset(10).sql()
2918            'SELECT x FROM tbl OFFSET 10'
2919
2920        Args:
2921            expression: the SQL code string to parse.
2922                This can also be an integer.
2923                If a `Offset` instance is passed, this is used as-is.
2924                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2925            dialect: the dialect used to parse the input expression.
2926            copy: if `False`, modify this expression instance in-place.
2927            opts: other options to use to parse the input expressions.
2928
2929        Returns:
2930            The modified Select expression.
2931        """
2932        return _apply_builder(
2933            expression=expression,
2934            instance=self,
2935            arg="offset",
2936            into=Offset,
2937            prefix="OFFSET",
2938            dialect=dialect,
2939            copy=copy,
2940            into_arg="expression",
2941            **opts,
2942        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def select( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2944    def select(
2945        self,
2946        *expressions: t.Optional[ExpOrStr],
2947        append: bool = True,
2948        dialect: DialectType = None,
2949        copy: bool = True,
2950        **opts,
2951    ) -> Select:
2952        """
2953        Append to or set the SELECT expressions.
2954
2955        Example:
2956            >>> Select().select("x", "y").sql()
2957            'SELECT x, y'
2958
2959        Args:
2960            *expressions: the SQL code strings to parse.
2961                If an `Expression` instance is passed, it will be used as-is.
2962            append: if `True`, add to any existing expressions.
2963                Otherwise, this resets the expressions.
2964            dialect: the dialect used to parse the input expressions.
2965            copy: if `False`, modify this expression instance in-place.
2966            opts: other options to use to parse the input expressions.
2967
2968        Returns:
2969            The modified Select expression.
2970        """
2971        return _apply_list_builder(
2972            *expressions,
2973            instance=self,
2974            arg="expressions",
2975            append=append,
2976            dialect=dialect,
2977            copy=copy,
2978            **opts,
2979        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def lateral( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2981    def lateral(
2982        self,
2983        *expressions: t.Optional[ExpOrStr],
2984        append: bool = True,
2985        dialect: DialectType = None,
2986        copy: bool = True,
2987        **opts,
2988    ) -> Select:
2989        """
2990        Append to or set the LATERAL expressions.
2991
2992        Example:
2993            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2994            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2995
2996        Args:
2997            *expressions: the SQL code strings to parse.
2998                If an `Expression` instance is passed, it will be used as-is.
2999            append: if `True`, add to any existing expressions.
3000                Otherwise, this resets the expressions.
3001            dialect: the dialect used to parse the input expressions.
3002            copy: if `False`, modify this expression instance in-place.
3003            opts: other options to use to parse the input expressions.
3004
3005        Returns:
3006            The modified Select expression.
3007        """
3008        return _apply_list_builder(
3009            *expressions,
3010            instance=self,
3011            arg="laterals",
3012            append=append,
3013            into=Lateral,
3014            prefix="LATERAL VIEW",
3015            dialect=dialect,
3016            copy=copy,
3017            **opts,
3018        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def join( self, expression: Union[str, Expression], on: Union[str, Expression, NoneType] = None, using: Union[str, Expression, Collection[Union[str, Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3020    def join(
3021        self,
3022        expression: ExpOrStr,
3023        on: t.Optional[ExpOrStr] = None,
3024        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
3025        append: bool = True,
3026        join_type: t.Optional[str] = None,
3027        join_alias: t.Optional[Identifier | str] = None,
3028        dialect: DialectType = None,
3029        copy: bool = True,
3030        **opts,
3031    ) -> Select:
3032        """
3033        Append to or set the JOIN expressions.
3034
3035        Example:
3036            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
3037            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
3038
3039            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
3040            'SELECT 1 FROM a JOIN b USING (x, y, z)'
3041
3042            Use `join_type` to change the type of join:
3043
3044            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
3045            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
3046
3047        Args:
3048            expression: the SQL code string to parse.
3049                If an `Expression` instance is passed, it will be used as-is.
3050            on: optionally specify the join "on" criteria as a SQL string.
3051                If an `Expression` instance is passed, it will be used as-is.
3052            using: optionally specify the join "using" criteria as a SQL string.
3053                If an `Expression` instance is passed, it will be used as-is.
3054            append: if `True`, add to any existing expressions.
3055                Otherwise, this resets the expressions.
3056            join_type: if set, alter the parsed join type.
3057            join_alias: an optional alias for the joined source.
3058            dialect: the dialect used to parse the input expressions.
3059            copy: if `False`, modify this expression instance in-place.
3060            opts: other options to use to parse the input expressions.
3061
3062        Returns:
3063            Select: the modified expression.
3064        """
3065        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3066
3067        try:
3068            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3069        except ParseError:
3070            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3071
3072        join = expression if isinstance(expression, Join) else Join(this=expression)
3073
3074        if isinstance(join.this, Select):
3075            join.this.replace(join.this.subquery())
3076
3077        if join_type:
3078            method: t.Optional[Token]
3079            side: t.Optional[Token]
3080            kind: t.Optional[Token]
3081
3082            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3083
3084            if method:
3085                join.set("method", method.text)
3086            if side:
3087                join.set("side", side.text)
3088            if kind:
3089                join.set("kind", kind.text)
3090
3091        if on:
3092            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3093            join.set("on", on)
3094
3095        if using:
3096            join = _apply_list_builder(
3097                *ensure_list(using),
3098                instance=join,
3099                arg="using",
3100                append=append,
3101                copy=copy,
3102                into=Identifier,
3103                **opts,
3104            )
3105
3106        if join_alias:
3107            join.set("this", alias_(join.this, join_alias, table=True))
3108
3109        return _apply_list_builder(
3110            join,
3111            instance=self,
3112            arg="joins",
3113            append=append,
3114            copy=copy,
3115            **opts,
3116        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on: optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using: optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type: if set, alter the parsed join type.
  • join_alias: an optional alias for the joined source.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3118    def where(
3119        self,
3120        *expressions: t.Optional[ExpOrStr],
3121        append: bool = True,
3122        dialect: DialectType = None,
3123        copy: bool = True,
3124        **opts,
3125    ) -> Select:
3126        """
3127        Append to or set the WHERE expressions.
3128
3129        Example:
3130            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3131            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3132
3133        Args:
3134            *expressions: the SQL code strings to parse.
3135                If an `Expression` instance is passed, it will be used as-is.
3136                Multiple expressions are combined with an AND operator.
3137            append: if `True`, AND the new expressions to any existing expression.
3138                Otherwise, this resets the expression.
3139            dialect: the dialect used to parse the input expressions.
3140            copy: if `False`, modify this expression instance in-place.
3141            opts: other options to use to parse the input expressions.
3142
3143        Returns:
3144            Select: the modified expression.
3145        """
3146        return _apply_conjunction_builder(
3147            *expressions,
3148            instance=self,
3149            arg="where",
3150            append=append,
3151            into=Where,
3152            dialect=dialect,
3153            copy=copy,
3154            **opts,
3155        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3157    def having(
3158        self,
3159        *expressions: t.Optional[ExpOrStr],
3160        append: bool = True,
3161        dialect: DialectType = None,
3162        copy: bool = True,
3163        **opts,
3164    ) -> Select:
3165        """
3166        Append to or set the HAVING expressions.
3167
3168        Example:
3169            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3170            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3171
3172        Args:
3173            *expressions: the SQL code strings to parse.
3174                If an `Expression` instance is passed, it will be used as-is.
3175                Multiple expressions are combined with an AND operator.
3176            append: if `True`, AND the new expressions to any existing expression.
3177                Otherwise, this resets the expression.
3178            dialect: the dialect used to parse the input expressions.
3179            copy: if `False`, modify this expression instance in-place.
3180            opts: other options to use to parse the input expressions.
3181
3182        Returns:
3183            The modified Select expression.
3184        """
3185        return _apply_conjunction_builder(
3186            *expressions,
3187            instance=self,
3188            arg="having",
3189            append=append,
3190            into=Having,
3191            dialect=dialect,
3192            copy=copy,
3193            **opts,
3194        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def window( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3196    def window(
3197        self,
3198        *expressions: t.Optional[ExpOrStr],
3199        append: bool = True,
3200        dialect: DialectType = None,
3201        copy: bool = True,
3202        **opts,
3203    ) -> Select:
3204        return _apply_list_builder(
3205            *expressions,
3206            instance=self,
3207            arg="windows",
3208            append=append,
3209            into=Window,
3210            dialect=dialect,
3211            copy=copy,
3212            **opts,
3213        )
def qualify( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3215    def qualify(
3216        self,
3217        *expressions: t.Optional[ExpOrStr],
3218        append: bool = True,
3219        dialect: DialectType = None,
3220        copy: bool = True,
3221        **opts,
3222    ) -> Select:
3223        return _apply_conjunction_builder(
3224            *expressions,
3225            instance=self,
3226            arg="qualify",
3227            append=append,
3228            into=Qualify,
3229            dialect=dialect,
3230            copy=copy,
3231            **opts,
3232        )
def distinct( self, *ons: Union[str, Expression, NoneType], distinct: bool = True, copy: bool = True) -> Select:
3234    def distinct(
3235        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3236    ) -> Select:
3237        """
3238        Set the OFFSET expression.
3239
3240        Example:
3241            >>> Select().from_("tbl").select("x").distinct().sql()
3242            'SELECT DISTINCT x FROM tbl'
3243
3244        Args:
3245            ons: the expressions to distinct on
3246            distinct: whether the Select should be distinct
3247            copy: if `False`, modify this expression instance in-place.
3248
3249        Returns:
3250            Select: the modified expression.
3251        """
3252        instance = maybe_copy(self, copy)
3253        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3254        instance.set("distinct", Distinct(on=on) if distinct else None)
3255        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table: Union[str, Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Create:
3257    def ctas(
3258        self,
3259        table: ExpOrStr,
3260        properties: t.Optional[t.Dict] = None,
3261        dialect: DialectType = None,
3262        copy: bool = True,
3263        **opts,
3264    ) -> Create:
3265        """
3266        Convert this expression to a CREATE TABLE AS statement.
3267
3268        Example:
3269            >>> Select().select("*").from_("tbl").ctas("x").sql()
3270            'CREATE TABLE x AS SELECT * FROM tbl'
3271
3272        Args:
3273            table: the SQL code string to parse as the table name.
3274                If another `Expression` instance is passed, it will be used as-is.
3275            properties: an optional mapping of table properties
3276            dialect: the dialect used to parse the input table.
3277            copy: if `False`, modify this expression instance in-place.
3278            opts: other options to use to parse the input table.
3279
3280        Returns:
3281            The new Create expression.
3282        """
3283        instance = maybe_copy(self, copy)
3284        table_expression = maybe_parse(
3285            table,
3286            into=Table,
3287            dialect=dialect,
3288            **opts,
3289        )
3290        properties_expression = None
3291        if properties:
3292            properties_expression = Properties.from_dict(properties)
3293
3294        return Create(
3295            this=table_expression,
3296            kind="table",
3297            expression=instance,
3298            properties=properties_expression,
3299        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table: the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties: an optional mapping of table properties
  • dialect: the dialect used to parse the input table.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input table.
Returns:

The new Create expression.

def lock( self, update: bool = True, copy: bool = True) -> Select:
3301    def lock(self, update: bool = True, copy: bool = True) -> Select:
3302        """
3303        Set the locking read mode for this expression.
3304
3305        Examples:
3306            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3307            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3308
3309            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3310            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3311
3312        Args:
3313            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3314            copy: if `False`, modify this expression instance in-place.
3315
3316        Returns:
3317            The modified expression.
3318        """
3319        inst = maybe_copy(self, copy)
3320        inst.set("locks", [Lock(update=update)])
3321
3322        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

def hint( self, *hints: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> Select:
3324    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3325        """
3326        Set hints for this expression.
3327
3328        Examples:
3329            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3330            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3331
3332        Args:
3333            hints: The SQL code strings to parse as the hints.
3334                If an `Expression` instance is passed, it will be used as-is.
3335            dialect: The dialect used to parse the hints.
3336            copy: If `False`, modify this expression instance in-place.
3337
3338        Returns:
3339            The modified expression.
3340        """
3341        inst = maybe_copy(self, copy)
3342        inst.set(
3343            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3344        )
3345
3346        return inst

Set hints for this expression.

Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
  • hints: The SQL code strings to parse as the hints. If an Expression instance is passed, it will be used as-is.
  • dialect: The dialect used to parse the hints.
  • copy: If False, modify this expression instance in-place.
Returns:

The modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

selects: List[Expression]
key = 'select'
class Subquery(DerivedTable, Unionable):
3361class Subquery(DerivedTable, Unionable):
3362    arg_types = {
3363        "this": True,
3364        "alias": False,
3365        "with": False,
3366        **QUERY_MODIFIERS,
3367    }
3368
3369    def unnest(self):
3370        """
3371        Returns the first non subquery.
3372        """
3373        expression = self
3374        while isinstance(expression, Subquery):
3375            expression = expression.this
3376        return expression
3377
3378    def unwrap(self) -> Subquery:
3379        expression = self
3380        while expression.same_parent and expression.is_wrapper:
3381            expression = t.cast(Subquery, expression.parent)
3382        return expression
3383
3384    @property
3385    def is_wrapper(self) -> bool:
3386        """
3387        Whether this Subquery acts as a simple wrapper around another expression.
3388
3389        SELECT * FROM (((SELECT * FROM t)))
3390                      ^
3391                      This corresponds to a "wrapper" Subquery node
3392        """
3393        return all(v is None for k, v in self.args.items() if k != "this")
3394
3395    @property
3396    def is_star(self) -> bool:
3397        return self.this.is_star
3398
3399    @property
3400    def output_name(self) -> str:
3401        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def unnest(self):
3369    def unnest(self):
3370        """
3371        Returns the first non subquery.
3372        """
3373        expression = self
3374        while isinstance(expression, Subquery):
3375            expression = expression.this
3376        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
3378    def unwrap(self) -> Subquery:
3379        expression = self
3380        while expression.same_parent and expression.is_wrapper:
3381            expression = t.cast(Subquery, expression.parent)
3382        return expression
is_wrapper: bool

Whether this Subquery acts as a simple wrapper around another expression.

SELECT * FROM (((SELECT * FROM t))) ^ This corresponds to a "wrapper" Subquery node

is_star: bool

Checks whether an expression is a star.

output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3404class TableSample(Expression):
3405    arg_types = {
3406        "this": False,
3407        "expressions": False,
3408        "method": False,
3409        "bucket_numerator": False,
3410        "bucket_denominator": False,
3411        "bucket_field": False,
3412        "percent": False,
3413        "rows": False,
3414        "size": False,
3415        "seed": False,
3416        "kind": False,
3417    }
arg_types = {'this': False, 'expressions': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False, 'kind': False}
key = 'tablesample'
class Tag(Expression):
3420class Tag(Expression):
3421    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3422
3423    arg_types = {
3424        "this": False,
3425        "prefix": False,
3426        "postfix": False,
3427    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3432class Pivot(Expression):
3433    arg_types = {
3434        "this": False,
3435        "alias": False,
3436        "expressions": False,
3437        "field": False,
3438        "unpivot": False,
3439        "using": False,
3440        "group": False,
3441        "columns": False,
3442        "include_nulls": False,
3443    }
arg_types = {'this': False, 'alias': False, 'expressions': False, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Condition):
3446class Window(Condition):
3447    arg_types = {
3448        "this": True,
3449        "partition_by": False,
3450        "order": False,
3451        "spec": False,
3452        "alias": False,
3453        "over": False,
3454        "first": False,
3455    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3458class WindowSpec(Expression):
3459    arg_types = {
3460        "kind": False,
3461        "start": False,
3462        "start_side": False,
3463        "end": False,
3464        "end_side": False,
3465    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3468class Where(Expression):
3469    pass
key = 'where'
class Star(Expression):
3472class Star(Expression):
3473    arg_types = {"except": False, "replace": False}
3474
3475    @property
3476    def name(self) -> str:
3477        return "*"
3478
3479    @property
3480    def output_name(self) -> str:
3481        return self.name
arg_types = {'except': False, 'replace': False}
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'star'
class Parameter(Condition):
3484class Parameter(Condition):
3485    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3488class SessionParameter(Condition):
3489    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3492class Placeholder(Condition):
3493    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3496class Null(Condition):
3497    arg_types: t.Dict[str, t.Any] = {}
3498
3499    @property
3500    def name(self) -> str:
3501        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3504class Boolean(Condition):
3505    pass
key = 'boolean'
class DataTypeParam(Expression):
3508class DataTypeParam(Expression):
3509    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3512class DataType(Expression):
3513    arg_types = {
3514        "this": True,
3515        "expressions": False,
3516        "nested": False,
3517        "values": False,
3518        "prefix": False,
3519        "kind": False,
3520    }
3521
3522    class Type(AutoName):
3523        ARRAY = auto()
3524        BIGDECIMAL = auto()
3525        BIGINT = auto()
3526        BIGSERIAL = auto()
3527        BINARY = auto()
3528        BIT = auto()
3529        BOOLEAN = auto()
3530        CHAR = auto()
3531        DATE = auto()
3532        DATEMULTIRANGE = auto()
3533        DATERANGE = auto()
3534        DATETIME = auto()
3535        DATETIME64 = auto()
3536        DECIMAL = auto()
3537        DOUBLE = auto()
3538        ENUM = auto()
3539        ENUM8 = auto()
3540        ENUM16 = auto()
3541        FIXEDSTRING = auto()
3542        FLOAT = auto()
3543        GEOGRAPHY = auto()
3544        GEOMETRY = auto()
3545        HLLSKETCH = auto()
3546        HSTORE = auto()
3547        IMAGE = auto()
3548        INET = auto()
3549        INT = auto()
3550        INT128 = auto()
3551        INT256 = auto()
3552        INT4MULTIRANGE = auto()
3553        INT4RANGE = auto()
3554        INT8MULTIRANGE = auto()
3555        INT8RANGE = auto()
3556        INTERVAL = auto()
3557        IPADDRESS = auto()
3558        IPPREFIX = auto()
3559        JSON = auto()
3560        JSONB = auto()
3561        LONGBLOB = auto()
3562        LONGTEXT = auto()
3563        LOWCARDINALITY = auto()
3564        MAP = auto()
3565        MEDIUMBLOB = auto()
3566        MEDIUMINT = auto()
3567        MEDIUMTEXT = auto()
3568        MONEY = auto()
3569        NCHAR = auto()
3570        NESTED = auto()
3571        NULL = auto()
3572        NULLABLE = auto()
3573        NUMMULTIRANGE = auto()
3574        NUMRANGE = auto()
3575        NVARCHAR = auto()
3576        OBJECT = auto()
3577        ROWVERSION = auto()
3578        SERIAL = auto()
3579        SET = auto()
3580        SMALLINT = auto()
3581        SMALLMONEY = auto()
3582        SMALLSERIAL = auto()
3583        STRUCT = auto()
3584        SUPER = auto()
3585        TEXT = auto()
3586        TINYBLOB = auto()
3587        TINYTEXT = auto()
3588        TIME = auto()
3589        TIMETZ = auto()
3590        TIMESTAMP = auto()
3591        TIMESTAMPLTZ = auto()
3592        TIMESTAMPTZ = auto()
3593        TINYINT = auto()
3594        TSMULTIRANGE = auto()
3595        TSRANGE = auto()
3596        TSTZMULTIRANGE = auto()
3597        TSTZRANGE = auto()
3598        UBIGINT = auto()
3599        UINT = auto()
3600        UINT128 = auto()
3601        UINT256 = auto()
3602        UMEDIUMINT = auto()
3603        UDECIMAL = auto()
3604        UNIQUEIDENTIFIER = auto()
3605        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3606        USERDEFINED = "USER-DEFINED"
3607        USMALLINT = auto()
3608        UTINYINT = auto()
3609        UUID = auto()
3610        VARBINARY = auto()
3611        VARCHAR = auto()
3612        VARIANT = auto()
3613        XML = auto()
3614        YEAR = auto()
3615
3616    TEXT_TYPES = {
3617        Type.CHAR,
3618        Type.NCHAR,
3619        Type.VARCHAR,
3620        Type.NVARCHAR,
3621        Type.TEXT,
3622    }
3623
3624    INTEGER_TYPES = {
3625        Type.INT,
3626        Type.TINYINT,
3627        Type.SMALLINT,
3628        Type.BIGINT,
3629        Type.INT128,
3630        Type.INT256,
3631    }
3632
3633    FLOAT_TYPES = {
3634        Type.FLOAT,
3635        Type.DOUBLE,
3636    }
3637
3638    NUMERIC_TYPES = {
3639        *INTEGER_TYPES,
3640        *FLOAT_TYPES,
3641    }
3642
3643    TEMPORAL_TYPES = {
3644        Type.TIME,
3645        Type.TIMETZ,
3646        Type.TIMESTAMP,
3647        Type.TIMESTAMPTZ,
3648        Type.TIMESTAMPLTZ,
3649        Type.DATE,
3650        Type.DATETIME,
3651        Type.DATETIME64,
3652    }
3653
3654    @classmethod
3655    def build(
3656        cls,
3657        dtype: str | DataType | DataType.Type,
3658        dialect: DialectType = None,
3659        udt: bool = False,
3660        **kwargs,
3661    ) -> DataType:
3662        """
3663        Constructs a DataType object.
3664
3665        Args:
3666            dtype: the data type of interest.
3667            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3668            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3669                DataType, thus creating a user-defined type.
3670            kawrgs: additional arguments to pass in the constructor of DataType.
3671
3672        Returns:
3673            The constructed DataType object.
3674        """
3675        from sqlglot import parse_one
3676
3677        if isinstance(dtype, str):
3678            if dtype.upper() == "UNKNOWN":
3679                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3680
3681            try:
3682                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3683            except ParseError:
3684                if udt:
3685                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3686                raise
3687        elif isinstance(dtype, DataType.Type):
3688            data_type_exp = DataType(this=dtype)
3689        elif isinstance(dtype, DataType):
3690            return dtype
3691        else:
3692            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3693
3694        return DataType(**{**data_type_exp.args, **kwargs})
3695
3696    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3697        """
3698        Checks whether this DataType matches one of the provided data types. Nested types or precision
3699        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3700
3701        Args:
3702            dtypes: the data types to compare this DataType to.
3703
3704        Returns:
3705            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3706        """
3707        for dtype in dtypes:
3708            other = DataType.build(dtype, udt=True)
3709
3710            if (
3711                other.expressions
3712                or self.this == DataType.Type.USERDEFINED
3713                or other.this == DataType.Type.USERDEFINED
3714            ):
3715                matches = self == other
3716            else:
3717                matches = self.this == other.this
3718
3719            if matches:
3720                return True
3721        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False, 'kind': False}
TEXT_TYPES = {<Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.TEXT: 'TEXT'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>}
INTEGER_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.INT128: 'INT128'>, <Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>, <Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.INT: 'INT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>}
TEMPORAL_TYPES = {<Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIMETZ: 'TIMETZ'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.DATE: 'DATE'>}
@classmethod
def build( cls, dtype: str | DataType | DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, udt: bool = False, **kwargs) -> DataType:
3654    @classmethod
3655    def build(
3656        cls,
3657        dtype: str | DataType | DataType.Type,
3658        dialect: DialectType = None,
3659        udt: bool = False,
3660        **kwargs,
3661    ) -> DataType:
3662        """
3663        Constructs a DataType object.
3664
3665        Args:
3666            dtype: the data type of interest.
3667            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3668            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3669                DataType, thus creating a user-defined type.
3670            kawrgs: additional arguments to pass in the constructor of DataType.
3671
3672        Returns:
3673            The constructed DataType object.
3674        """
3675        from sqlglot import parse_one
3676
3677        if isinstance(dtype, str):
3678            if dtype.upper() == "UNKNOWN":
3679                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3680
3681            try:
3682                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3683            except ParseError:
3684                if udt:
3685                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3686                raise
3687        elif isinstance(dtype, DataType.Type):
3688            data_type_exp = DataType(this=dtype)
3689        elif isinstance(dtype, DataType):
3690            return dtype
3691        else:
3692            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3693
3694        return DataType(**{**data_type_exp.args, **kwargs})

Constructs a DataType object.

Arguments:
  • dtype: the data type of interest.
  • dialect: the dialect to use for parsing dtype, in case it's a string.
  • udt: when set to True, dtype will be used as-is if it can't be parsed into a DataType, thus creating a user-defined type.
  • kawrgs: additional arguments to pass in the constructor of DataType.
Returns:

The constructed DataType object.

def is_type( self, *dtypes: str | DataType | DataType.Type) -> bool:
3696    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3697        """
3698        Checks whether this DataType matches one of the provided data types. Nested types or precision
3699        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3700
3701        Args:
3702            dtypes: the data types to compare this DataType to.
3703
3704        Returns:
3705            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3706        """
3707        for dtype in dtypes:
3708            other = DataType.build(dtype, udt=True)
3709
3710            if (
3711                other.expressions
3712                or self.this == DataType.Type.USERDEFINED
3713                or other.this == DataType.Type.USERDEFINED
3714            ):
3715                matches = self == other
3716            else:
3717                matches = self.this == other.this
3718
3719            if matches:
3720                return True
3721        return False

Checks whether this DataType matches one of the provided data types. Nested types or precision will be compared using "structural equivalence" semantics, so e.g. array != array.

Arguments:
  • dtypes: the data types to compare this DataType to.
Returns:

True, if and only if there is a type in dtypes which is equal to this DataType.

key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3522    class Type(AutoName):
3523        ARRAY = auto()
3524        BIGDECIMAL = auto()
3525        BIGINT = auto()
3526        BIGSERIAL = auto()
3527        BINARY = auto()
3528        BIT = auto()
3529        BOOLEAN = auto()
3530        CHAR = auto()
3531        DATE = auto()
3532        DATEMULTIRANGE = auto()
3533        DATERANGE = auto()
3534        DATETIME = auto()
3535        DATETIME64 = auto()
3536        DECIMAL = auto()
3537        DOUBLE = auto()
3538        ENUM = auto()
3539        ENUM8 = auto()
3540        ENUM16 = auto()
3541        FIXEDSTRING = auto()
3542        FLOAT = auto()
3543        GEOGRAPHY = auto()
3544        GEOMETRY = auto()
3545        HLLSKETCH = auto()
3546        HSTORE = auto()
3547        IMAGE = auto()
3548        INET = auto()
3549        INT = auto()
3550        INT128 = auto()
3551        INT256 = auto()
3552        INT4MULTIRANGE = auto()
3553        INT4RANGE = auto()
3554        INT8MULTIRANGE = auto()
3555        INT8RANGE = auto()
3556        INTERVAL = auto()
3557        IPADDRESS = auto()
3558        IPPREFIX = auto()
3559        JSON = auto()
3560        JSONB = auto()
3561        LONGBLOB = auto()
3562        LONGTEXT = auto()
3563        LOWCARDINALITY = auto()
3564        MAP = auto()
3565        MEDIUMBLOB = auto()
3566        MEDIUMINT = auto()
3567        MEDIUMTEXT = auto()
3568        MONEY = auto()
3569        NCHAR = auto()
3570        NESTED = auto()
3571        NULL = auto()
3572        NULLABLE = auto()
3573        NUMMULTIRANGE = auto()
3574        NUMRANGE = auto()
3575        NVARCHAR = auto()
3576        OBJECT = auto()
3577        ROWVERSION = auto()
3578        SERIAL = auto()
3579        SET = auto()
3580        SMALLINT = auto()
3581        SMALLMONEY = auto()
3582        SMALLSERIAL = auto()
3583        STRUCT = auto()
3584        SUPER = auto()
3585        TEXT = auto()
3586        TINYBLOB = auto()
3587        TINYTEXT = auto()
3588        TIME = auto()
3589        TIMETZ = auto()
3590        TIMESTAMP = auto()
3591        TIMESTAMPLTZ = auto()
3592        TIMESTAMPTZ = auto()
3593        TINYINT = auto()
3594        TSMULTIRANGE = auto()
3595        TSRANGE = auto()
3596        TSTZMULTIRANGE = auto()
3597        TSTZRANGE = auto()
3598        UBIGINT = auto()
3599        UINT = auto()
3600        UINT128 = auto()
3601        UINT256 = auto()
3602        UMEDIUMINT = auto()
3603        UDECIMAL = auto()
3604        UNIQUEIDENTIFIER = auto()
3605        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3606        USERDEFINED = "USER-DEFINED"
3607        USMALLINT = auto()
3608        UTINYINT = auto()
3609        UUID = auto()
3610        VARBINARY = auto()
3611        VARCHAR = auto()
3612        VARIANT = auto()
3613        XML = auto()
3614        YEAR = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
ENUM = <Type.ENUM: 'ENUM'>
ENUM8 = <Type.ENUM8: 'ENUM8'>
ENUM16 = <Type.ENUM16: 'ENUM16'>
FIXEDSTRING = <Type.FIXEDSTRING: 'FIXEDSTRING'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
LOWCARDINALITY = <Type.LOWCARDINALITY: 'LOWCARDINALITY'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMINT = <Type.MEDIUMINT: 'MEDIUMINT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NESTED = <Type.NESTED: 'NESTED'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TINYBLOB = <Type.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <Type.TINYTEXT: 'TINYTEXT'>
TIME = <Type.TIME: 'TIME'>
TIMETZ = <Type.TIMETZ: 'TIMETZ'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UMEDIUMINT = <Type.UMEDIUMINT: 'UMEDIUMINT'>
UDECIMAL = <Type.UDECIMAL: 'UDECIMAL'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
YEAR = <Type.YEAR: 'YEAR'>
Inherited Members
enum.Enum
name
value
class PseudoType(DataType):
3725class PseudoType(DataType):
3726    arg_types = {"this": True}
arg_types = {'this': True}
key = 'pseudotype'
class ObjectIdentifier(DataType):
3730class ObjectIdentifier(DataType):
3731    arg_types = {"this": True}
arg_types = {'this': True}
key = 'objectidentifier'
class SubqueryPredicate(Predicate):
3735class SubqueryPredicate(Predicate):
3736    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3739class All(SubqueryPredicate):
3740    pass
key = 'all'
class Any(SubqueryPredicate):
3743class Any(SubqueryPredicate):
3744    pass
key = 'any'
class Exists(SubqueryPredicate):
3747class Exists(SubqueryPredicate):
3748    pass
key = 'exists'
class Command(Expression):
3753class Command(Expression):
3754    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3757class Transaction(Expression):
3758    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3761class Commit(Expression):
3762    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3765class Rollback(Expression):
3766    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3769class AlterTable(Expression):
3770    arg_types = {"this": True, "actions": True, "exists": False, "only": False}
arg_types = {'this': True, 'actions': True, 'exists': False, 'only': False}
key = 'altertable'
class AddConstraint(Expression):
3773class AddConstraint(Expression):
3774    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3777class DropPartition(Expression):
3778    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3782class Binary(Condition):
3783    arg_types = {"this": True, "expression": True}
3784
3785    @property
3786    def left(self):
3787        return self.this
3788
3789    @property
3790    def right(self):
3791        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3794class Add(Binary):
3795    pass
key = 'add'
class Connector(Binary):
3798class Connector(Binary):
3799    pass
key = 'connector'
class And(Connector):
3802class And(Connector):
3803    pass
key = 'and'
class Or(Connector):
3806class Or(Connector):
3807    pass
key = 'or'
class BitwiseAnd(Binary):
3810class BitwiseAnd(Binary):
3811    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3814class BitwiseLeftShift(Binary):
3815    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3818class BitwiseOr(Binary):
3819    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3822class BitwiseRightShift(Binary):
3823    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3826class BitwiseXor(Binary):
3827    pass
key = 'bitwisexor'
class Div(Binary):
3830class Div(Binary):
3831    pass
key = 'div'
class Overlaps(Binary):
3834class Overlaps(Binary):
3835    pass
key = 'overlaps'
class Dot(Binary):
3838class Dot(Binary):
3839    @property
3840    def name(self) -> str:
3841        return self.expression.name
3842
3843    @property
3844    def output_name(self) -> str:
3845        return self.name
3846
3847    @classmethod
3848    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3849        """Build a Dot object with a sequence of expressions."""
3850        if len(expressions) < 2:
3851            raise ValueError(f"Dot requires >= 2 expressions.")
3852
3853        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
@classmethod
def build( self, expressions: Sequence[Expression]) -> Dot:
3847    @classmethod
3848    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3849        """Build a Dot object with a sequence of expressions."""
3850        if len(expressions) < 2:
3851            raise ValueError(f"Dot requires >= 2 expressions.")
3852
3853        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3856class DPipe(Binary):
3857    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3860class SafeDPipe(DPipe):
3861    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3864class EQ(Binary, Predicate):
3865    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3868class NullSafeEQ(Binary, Predicate):
3869    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3872class NullSafeNEQ(Binary, Predicate):
3873    pass
key = 'nullsafeneq'
class Distance(Binary):
3876class Distance(Binary):
3877    pass
key = 'distance'
class Escape(Binary):
3880class Escape(Binary):
3881    pass
key = 'escape'
class Glob(Binary, Predicate):
3884class Glob(Binary, Predicate):
3885    pass
key = 'glob'
class GT(Binary, Predicate):
3888class GT(Binary, Predicate):
3889    pass
key = 'gt'
class GTE(Binary, Predicate):
3892class GTE(Binary, Predicate):
3893    pass
key = 'gte'
class ILike(Binary, Predicate):
3896class ILike(Binary, Predicate):
3897    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3900class ILikeAny(Binary, Predicate):
3901    pass
key = 'ilikeany'
class IntDiv(Binary):
3904class IntDiv(Binary):
3905    pass
key = 'intdiv'
class Is(Binary, Predicate):
3908class Is(Binary, Predicate):
3909    pass
key = 'is'
class Kwarg(Binary):
3912class Kwarg(Binary):
3913    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

key = 'kwarg'
class Like(Binary, Predicate):
3916class Like(Binary, Predicate):
3917    pass
key = 'like'
class LikeAny(Binary, Predicate):
3920class LikeAny(Binary, Predicate):
3921    pass
key = 'likeany'
class LT(Binary, Predicate):
3924class LT(Binary, Predicate):
3925    pass
key = 'lt'
class LTE(Binary, Predicate):
3928class LTE(Binary, Predicate):
3929    pass
key = 'lte'
class Mod(Binary):
3932class Mod(Binary):
3933    pass
key = 'mod'
class Mul(Binary):
3936class Mul(Binary):
3937    pass
key = 'mul'
class NEQ(Binary, Predicate):
3940class NEQ(Binary, Predicate):
3941    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3944class SimilarTo(Binary, Predicate):
3945    pass
key = 'similarto'
class Slice(Binary):
3948class Slice(Binary):
3949    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3952class Sub(Binary):
3953    pass
key = 'sub'
class ArrayOverlaps(Binary):
3956class ArrayOverlaps(Binary):
3957    pass
key = 'arrayoverlaps'
class Unary(Condition):
3962class Unary(Condition):
3963    pass
key = 'unary'
class BitwiseNot(Unary):
3966class BitwiseNot(Unary):
3967    pass
key = 'bitwisenot'
class Not(Unary):
3970class Not(Unary):
3971    pass
key = 'not'
class Paren(Unary):
3974class Paren(Unary):
3975    arg_types = {"this": True, "with": False}
3976
3977    @property
3978    def output_name(self) -> str:
3979        return self.this.name
arg_types = {'this': True, 'with': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'paren'
class Neg(Unary):
3982class Neg(Unary):
3983    pass
key = 'neg'
class Alias(Expression):
3986class Alias(Expression):
3987    arg_types = {"this": True, "alias": False}
3988
3989    @property
3990    def output_name(self) -> str:
3991        return self.alias
arg_types = {'this': True, 'alias': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'alias'
class Aliases(Expression):
3994class Aliases(Expression):
3995    arg_types = {"this": True, "expressions": True}
3996
3997    @property
3998    def aliases(self):
3999        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
4002class AtTimeZone(Expression):
4003    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
4006class Between(Predicate):
4007    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
4010class Bracket(Condition):
4011    arg_types = {"this": True, "expressions": True}
4012
4013    @property
4014    def output_name(self) -> str:
4015        if len(self.expressions) == 1:
4016            return self.expressions[0].output_name
4017
4018        return super().output_name
arg_types = {'this': True, 'expressions': True}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'bracket'
class SafeBracket(Bracket):
4021class SafeBracket(Bracket):
4022    """Represents array lookup where OOB index yields NULL instead of causing a failure."""

Represents array lookup where OOB index yields NULL instead of causing a failure.

key = 'safebracket'
class Distinct(Expression):
4025class Distinct(Expression):
4026    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
4029class In(Predicate):
4030    arg_types = {
4031        "this": True,
4032        "expressions": False,
4033        "query": False,
4034        "unnest": False,
4035        "field": False,
4036        "is_global": False,
4037    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
4040class TimeUnit(Expression):
4041    """Automatically converts unit arg into a var."""
4042
4043    arg_types = {"unit": False}
4044
4045    def __init__(self, **args):
4046        unit = args.get("unit")
4047        if isinstance(unit, (Column, Literal)):
4048            args["unit"] = Var(this=unit.name)
4049        elif isinstance(unit, Week):
4050            unit.set("this", Var(this=unit.this.name))
4051
4052        super().__init__(**args)
4053
4054    @property
4055    def unit(self) -> t.Optional[Var]:
4056        return self.args.get("unit")

Automatically converts unit arg into a var.

TimeUnit(**args)
4045    def __init__(self, **args):
4046        unit = args.get("unit")
4047        if isinstance(unit, (Column, Literal)):
4048            args["unit"] = Var(this=unit.name)
4049        elif isinstance(unit, Week):
4050            unit.set("this", Var(this=unit.this.name))
4051
4052        super().__init__(**args)
arg_types = {'unit': False}
unit: Optional[Var]
key = 'timeunit'
class IntervalOp(TimeUnit):
4059class IntervalOp(TimeUnit):
4060    arg_types = {"unit": True, "expression": True}
4061
4062    def interval(self):
4063        return Interval(
4064            this=self.expression.copy(),
4065            unit=self.unit.copy(),
4066        )
arg_types = {'unit': True, 'expression': True}
def interval(self):
4062    def interval(self):
4063        return Interval(
4064            this=self.expression.copy(),
4065            unit=self.unit.copy(),
4066        )
key = 'intervalop'
class IntervalSpan(DataType):
4072class IntervalSpan(DataType):
4073    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'intervalspan'
class Interval(TimeUnit):
4076class Interval(TimeUnit):
4077    arg_types = {"this": False, "unit": False}
arg_types = {'this': False, 'unit': False}
key = 'interval'
class IgnoreNulls(Expression):
4080class IgnoreNulls(Expression):
4081    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4084class RespectNulls(Expression):
4085    pass
key = 'respectnulls'
class Func(Condition):
4089class Func(Condition):
4090    """
4091    The base class for all function expressions.
4092
4093    Attributes:
4094        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4095            treated as a variable length argument and the argument's value will be stored as a list.
4096        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4097            for this function expression. These values are used to map this node to a name during parsing
4098            as well as to provide the function's name during SQL string generation. By default the SQL
4099            name is set to the expression's class name transformed to snake case.
4100    """
4101
4102    is_var_len_args = False
4103
4104    @classmethod
4105    def from_arg_list(cls, args):
4106        if cls.is_var_len_args:
4107            all_arg_keys = list(cls.arg_types)
4108            # If this function supports variable length argument treat the last argument as such.
4109            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4110            num_non_var = len(non_var_len_arg_keys)
4111
4112            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4113            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4114        else:
4115            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4116
4117        return cls(**args_dict)
4118
4119    @classmethod
4120    def sql_names(cls):
4121        if cls is Func:
4122            raise NotImplementedError(
4123                "SQL name is only supported by concrete function implementations"
4124            )
4125        if "_sql_names" not in cls.__dict__:
4126            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4127        return cls._sql_names
4128
4129    @classmethod
4130    def sql_name(cls):
4131        return cls.sql_names()[0]
4132
4133    @classmethod
4134    def default_parser_mappings(cls):
4135        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
is_var_len_args = False
@classmethod
def from_arg_list(cls, args):
4104    @classmethod
4105    def from_arg_list(cls, args):
4106        if cls.is_var_len_args:
4107            all_arg_keys = list(cls.arg_types)
4108            # If this function supports variable length argument treat the last argument as such.
4109            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4110            num_non_var = len(non_var_len_arg_keys)
4111
4112            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4113            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4114        else:
4115            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4116
4117        return cls(**args_dict)
@classmethod
def sql_names(cls):
4119    @classmethod
4120    def sql_names(cls):
4121        if cls is Func:
4122            raise NotImplementedError(
4123                "SQL name is only supported by concrete function implementations"
4124            )
4125        if "_sql_names" not in cls.__dict__:
4126            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4127        return cls._sql_names
@classmethod
def sql_name(cls):
4129    @classmethod
4130    def sql_name(cls):
4131        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4133    @classmethod
4134    def default_parser_mappings(cls):
4135        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4138class AggFunc(Func):
4139    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4142class ParameterizedAgg(AggFunc):
4143    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4146class Abs(Func):
4147    pass
key = 'abs'
class Transform(Func):
4151class Transform(Func):
4152    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4155class Anonymous(Func):
4156    arg_types = {"this": True, "expressions": False}
4157    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4162class Hll(AggFunc):
4163    arg_types = {"this": True, "expressions": False}
4164    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4167class ApproxDistinct(AggFunc):
4168    arg_types = {"this": True, "accuracy": False}
4169    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4172class Array(Func):
4173    arg_types = {"expressions": False}
4174    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4178class ToChar(Func):
4179    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4182class GenerateSeries(Func):
4183    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4186class ArrayAgg(AggFunc):
4187    pass
key = 'arrayagg'
class ArrayAll(Func):
4190class ArrayAll(Func):
4191    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4194class ArrayAny(Func):
4195    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4198class ArrayConcat(Func):
4199    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4200    arg_types = {"this": True, "expressions": False}
4201    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4204class ArrayContains(Binary, Func):
4205    pass
key = 'arraycontains'
class ArrayContained(Binary):
4208class ArrayContained(Binary):
4209    pass
key = 'arraycontained'
class ArrayFilter(Func):
4212class ArrayFilter(Func):
4213    arg_types = {"this": True, "expression": True}
4214    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4217class ArrayJoin(Func):
4218    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4221class ArraySize(Func):
4222    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4225class ArraySort(Func):
4226    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4229class ArraySum(Func):
4230    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4233class ArrayUnionAgg(AggFunc):
4234    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4237class Avg(AggFunc):
4238    pass
key = 'avg'
class AnyValue(AggFunc):
4241class AnyValue(AggFunc):
4242    arg_types = {"this": True, "having": False, "max": False, "ignore_nulls": False}
arg_types = {'this': True, 'having': False, 'max': False, 'ignore_nulls': False}
key = 'anyvalue'
class First(Func):
4245class First(Func):
4246    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4249class Last(Func):
4250    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4253class Case(Func):
4254    arg_types = {"this": False, "ifs": True, "default": False}
4255
4256    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4257        instance = maybe_copy(self, copy)
4258        instance.append(
4259            "ifs",
4260            If(
4261                this=maybe_parse(condition, copy=copy, **opts),
4262                true=maybe_parse(then, copy=copy, **opts),
4263            ),
4264        )
4265        return instance
4266
4267    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4268        instance = maybe_copy(self, copy)
4269        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4270        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, Expression], then: Union[str, Expression], copy: bool = True, **opts) -> Case:
4256    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4257        instance = maybe_copy(self, copy)
4258        instance.append(
4259            "ifs",
4260            If(
4261                this=maybe_parse(condition, copy=copy, **opts),
4262                true=maybe_parse(then, copy=copy, **opts),
4263            ),
4264        )
4265        return instance
def else_( self, condition: Union[str, Expression], copy: bool = True, **opts) -> Case:
4267    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4268        instance = maybe_copy(self, copy)
4269        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4270        return instance
key = 'case'
class Cast(Func):
4273class Cast(Func):
4274    arg_types = {"this": True, "to": True, "format": False}
4275
4276    @property
4277    def name(self) -> str:
4278        return self.this.name
4279
4280    @property
4281    def to(self) -> DataType:
4282        return self.args["to"]
4283
4284    @property
4285    def output_name(self) -> str:
4286        return self.name
4287
4288    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4289        """
4290        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4291        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4292        array<int> != array<float>.
4293
4294        Args:
4295            dtypes: the data types to compare this Cast's DataType to.
4296
4297        Returns:
4298            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4299        """
4300        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True, 'format': False}
name: str
to: DataType
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
def is_type( self, *dtypes: str | DataType | DataType.Type) -> bool:
4288    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4289        """
4290        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4291        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4292        array<int> != array<float>.
4293
4294        Args:
4295            dtypes: the data types to compare this Cast's DataType to.
4296
4297        Returns:
4298            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4299        """
4300        return self.to.is_type(*dtypes)

Checks whether this Cast's DataType matches one of the provided data types. Nested types like arrays or structs will be compared using "structural equivalence" semantics, so e.g. array != array.

Arguments:
  • dtypes: the data types to compare this Cast's DataType to.
Returns:

True, if and only if there is a type in dtypes which is equal to this Cast's DataType.

key = 'cast'
class TryCast(Cast):
4303class TryCast(Cast):
4304    pass
key = 'trycast'
class CastToStrType(Func):
4307class CastToStrType(Func):
4308    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary, Func):
4311class Collate(Binary, Func):
4312    pass
key = 'collate'
class Ceil(Func):
4315class Ceil(Func):
4316    arg_types = {"this": True, "decimals": False}
4317    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4320class Coalesce(Func):
4321    arg_types = {"this": True, "expressions": False}
4322    is_var_len_args = True
4323    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Chr(Func):
4326class Chr(Func):
4327    arg_types = {"this": True, "charset": False, "expressions": False}
4328    is_var_len_args = True
4329    _sql_names = ["CHR", "CHAR"]
arg_types = {'this': True, 'charset': False, 'expressions': False}
is_var_len_args = True
key = 'chr'
class Concat(Func):
4332class Concat(Func):
4333    arg_types = {"expressions": True}
4334    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4337class SafeConcat(Concat):
4338    pass
key = 'safeconcat'
class ConcatWs(Concat):
4341class ConcatWs(Concat):
4342    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4345class Count(AggFunc):
4346    arg_types = {"this": False, "expressions": False}
4347    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4350class CountIf(AggFunc):
4351    pass
key = 'countif'
class CurrentDate(Func):
4354class CurrentDate(Func):
4355    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4358class CurrentDatetime(Func):
4359    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4362class CurrentTime(Func):
4363    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4366class CurrentTimestamp(Func):
4367    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4370class CurrentUser(Func):
4371    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, IntervalOp):
4374class DateAdd(Func, IntervalOp):
4375    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, IntervalOp):
4378class DateSub(Func, IntervalOp):
4379    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4382class DateDiff(Func, TimeUnit):
4383    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4384    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4387class DateTrunc(Func):
4388    arg_types = {"unit": True, "this": True, "zone": False}
4389
4390    @property
4391    def unit(self) -> Expression:
4392        return self.args["unit"]
arg_types = {'unit': True, 'this': True, 'zone': False}
unit: Expression
key = 'datetrunc'
class DatetimeAdd(Func, IntervalOp):
4395class DatetimeAdd(Func, IntervalOp):
4396    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, IntervalOp):
4399class DatetimeSub(Func, IntervalOp):
4400    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4403class DatetimeDiff(Func, TimeUnit):
4404    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4407class DatetimeTrunc(Func, TimeUnit):
4408    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4411class DayOfWeek(Func):
4412    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4415class DayOfMonth(Func):
4416    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4419class DayOfYear(Func):
4420    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class ToDays(Func):
4423class ToDays(Func):
4424    pass
key = 'todays'
class WeekOfYear(Func):
4427class WeekOfYear(Func):
4428    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4431class MonthsBetween(Func):
4432    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4435class LastDateOfMonth(Func):
4436    pass
key = 'lastdateofmonth'
class Extract(Func):
4439class Extract(Func):
4440    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class Timestamp(Func):
4443class Timestamp(Func):
4444    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'timestamp'
class TimestampAdd(Func, TimeUnit):
4447class TimestampAdd(Func, TimeUnit):
4448    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4451class TimestampSub(Func, TimeUnit):
4452    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4455class TimestampDiff(Func, TimeUnit):
4456    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4459class TimestampTrunc(Func, TimeUnit):
4460    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4463class TimeAdd(Func, TimeUnit):
4464    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4467class TimeSub(Func, TimeUnit):
4468    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4471class TimeDiff(Func, TimeUnit):
4472    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4475class TimeTrunc(Func, TimeUnit):
4476    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4479class DateFromParts(Func):
4480    _sql_names = ["DATEFROMPARTS"]
4481    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4484class DateStrToDate(Func):
4485    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4488class DateToDateStr(Func):
4489    pass
key = 'datetodatestr'
class DateToDi(Func):
4492class DateToDi(Func):
4493    pass
key = 'datetodi'
class Date(Func):
4497class Date(Func):
4498    arg_types = {"this": False, "zone": False, "expressions": False}
4499    is_var_len_args = True
arg_types = {'this': False, 'zone': False, 'expressions': False}
is_var_len_args = True
key = 'date'
class Day(Func):
4502class Day(Func):
4503    pass
key = 'day'
class Decode(Func):
4506class Decode(Func):
4507    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4510class DiToDate(Func):
4511    pass
key = 'ditodate'
class Encode(Func):
4514class Encode(Func):
4515    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4518class Exp(Func):
4519    pass
key = 'exp'
class Explode(Func):
4522class Explode(Func):
4523    pass
key = 'explode'
class Floor(Func):
4526class Floor(Func):
4527    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4530class FromBase64(Func):
4531    pass
key = 'frombase64'
class ToBase64(Func):
4534class ToBase64(Func):
4535    pass
key = 'tobase64'
class Greatest(Func):
4538class Greatest(Func):
4539    arg_types = {"this": True, "expressions": False}
4540    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(AggFunc):
4543class GroupConcat(AggFunc):
4544    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4547class Hex(Func):
4548    pass
key = 'hex'
class Xor(Connector, Func):
4551class Xor(Connector, Func):
4552    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4555class If(Func):
4556    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4559class Initcap(Func):
4560    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4563class IsNan(Func):
4564    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class FormatJson(Expression):
4567class FormatJson(Expression):
4568    pass
key = 'formatjson'
class JSONKeyValue(Expression):
4571class JSONKeyValue(Expression):
4572    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4575class JSONObject(Func):
4576    arg_types = {
4577        "expressions": False,
4578        "null_handling": False,
4579        "unique_keys": False,
4580        "return_type": False,
4581        "encoding": False,
4582    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'encoding': False}
key = 'jsonobject'
class JSONArray(Func):
4586class JSONArray(Func):
4587    arg_types = {
4588        "expressions": True,
4589        "null_handling": False,
4590        "return_type": False,
4591        "strict": False,
4592    }
arg_types = {'expressions': True, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarray'
class JSONArrayAgg(Func):
4596class JSONArrayAgg(Func):
4597    arg_types = {
4598        "this": True,
4599        "order": False,
4600        "null_handling": False,
4601        "return_type": False,
4602        "strict": False,
4603    }
arg_types = {'this': True, 'order': False, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarrayagg'
class JSONColumnDef(Expression):
4608class JSONColumnDef(Expression):
4609    arg_types = {"this": True, "kind": False, "path": False}
arg_types = {'this': True, 'kind': False, 'path': False}
key = 'jsoncolumndef'
class JSONTable(Func):
4613class JSONTable(Func):
4614    arg_types = {
4615        "this": True,
4616        "expressions": True,
4617        "path": False,
4618        "error_handling": False,
4619        "empty_handling": False,
4620    }
arg_types = {'this': True, 'expressions': True, 'path': False, 'error_handling': False, 'empty_handling': False}
key = 'jsontable'
class OpenJSONColumnDef(Expression):
4623class OpenJSONColumnDef(Expression):
4624    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
arg_types = {'this': True, 'kind': True, 'path': False, 'as_json': False}
key = 'openjsoncolumndef'
class OpenJSON(Func):
4627class OpenJSON(Func):
4628    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4631class JSONBContains(Binary):
4632    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4635class JSONExtract(Binary, Func):
4636    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4639class JSONExtractScalar(JSONExtract):
4640    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4643class JSONBExtract(JSONExtract):
4644    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4647class JSONBExtractScalar(JSONExtract):
4648    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4651class JSONFormat(Func):
4652    arg_types = {"this": False, "options": False}
4653    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4657class JSONArrayContains(Binary, Predicate, Func):
4658    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class ParseJSON(Func):
4661class ParseJSON(Func):
4662    # BigQuery, Snowflake have PARSE_JSON, Presto has JSON_PARSE
4663    _sql_names = ["PARSE_JSON", "JSON_PARSE"]
key = 'parsejson'
class Least(Func):
4666class Least(Func):
4667    arg_types = {"this": True, "expressions": False}
4668    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4671class Left(Func):
4672    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4679class Length(Func):
4680    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4683class Levenshtein(Func):
4684    arg_types = {
4685        "this": True,
4686        "expression": False,
4687        "ins_cost": False,
4688        "del_cost": False,
4689        "sub_cost": False,
4690    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4693class Ln(Func):
4694    pass
key = 'ln'
class Log(Func):
4697class Log(Func):
4698    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4701class Log2(Func):
4702    pass
key = 'log2'
class Log10(Func):
4705class Log10(Func):
4706    pass
key = 'log10'
class LogicalOr(AggFunc):
4709class LogicalOr(AggFunc):
4710    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4713class LogicalAnd(AggFunc):
4714    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4717class Lower(Func):
4718    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4721class Map(Func):
4722    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4725class MapFromEntries(Func):
4726    pass
key = 'mapfromentries'
class StarMap(Func):
4729class StarMap(Func):
4730    pass
key = 'starmap'
class VarMap(Func):
4733class VarMap(Func):
4734    arg_types = {"keys": True, "values": True}
4735    is_var_len_args = True
4736
4737    @property
4738    def keys(self) -> t.List[Expression]:
4739        return self.args["keys"].expressions
4740
4741    @property
4742    def values(self) -> t.List[Expression]:
4743        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
keys: List[Expression]
values: List[Expression]
key = 'varmap'
class MatchAgainst(Func):
4747class MatchAgainst(Func):
4748    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4751class Max(AggFunc):
4752    arg_types = {"this": True, "expressions": False}
4753    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4756class MD5(Func):
4757    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4761class MD5Digest(Func):
4762    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4765class Min(AggFunc):
4766    arg_types = {"this": True, "expressions": False}
4767    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4770class Month(Func):
4771    pass
key = 'month'
class Nvl2(Func):
4774class Nvl2(Func):
4775    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4778class Posexplode(Func):
4779    pass
key = 'posexplode'
class Predict(Func):
4783class Predict(Func):
4784    arg_types = {"this": True, "expression": True, "params_struct": False}
arg_types = {'this': True, 'expression': True, 'params_struct': False}
key = 'predict'
class Pow(Binary, Func):
4787class Pow(Binary, Func):
4788    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4791class PercentileCont(AggFunc):
4792    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4795class PercentileDisc(AggFunc):
4796    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4799class Quantile(AggFunc):
4800    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4803class ApproxQuantile(Quantile):
4804    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
arg_types = {'this': True, 'quantile': True, 'accuracy': False, 'weight': False}
key = 'approxquantile'
class RangeN(Func):
4807class RangeN(Func):
4808    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4811class ReadCSV(Func):
4812    _sql_names = ["READ_CSV"]
4813    is_var_len_args = True
4814    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4817class Reduce(Func):
4818    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
arg_types = {'this': True, 'initial': True, 'merge': True, 'finish': False}
key = 'reduce'
class RegexpExtract(Func):
4821class RegexpExtract(Func):
4822    arg_types = {
4823        "this": True,
4824        "expression": True,
4825        "position": False,
4826        "occurrence": False,
4827        "parameters": False,
4828        "group": False,
4829    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4832class RegexpReplace(Func):
4833    arg_types = {
4834        "this": True,
4835        "expression": True,
4836        "replacement": True,
4837        "position": False,
4838        "occurrence": False,
4839        "parameters": False,
4840    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4843class RegexpLike(Binary, Func):
4844    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4847class RegexpILike(Func):
4848    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4853class RegexpSplit(Func):
4854    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4857class Repeat(Func):
4858    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4861class Round(Func):
4862    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4865class RowNumber(Func):
4866    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4869class SafeDivide(Func):
4870    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4873class SetAgg(AggFunc):
4874    pass
key = 'setagg'
class SHA(Func):
4877class SHA(Func):
4878    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4881class SHA2(Func):
4882    _sql_names = ["SHA2"]
4883    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4886class SortArray(Func):
4887    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4890class Split(Func):
4891    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4896class Substring(Func):
4897    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4900class StandardHash(Func):
4901    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4904class StartsWith(Func):
4905    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4906    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4909class StrPosition(Func):
4910    arg_types = {
4911        "this": True,
4912        "substr": True,
4913        "position": False,
4914        "instance": False,
4915    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4918class StrToDate(Func):
4919    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4922class StrToTime(Func):
4923    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4928class StrToUnix(Func):
4929    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4934class StrToMap(Func):
4935    arg_types = {
4936        "this": True,
4937        "pair_delim": False,
4938        "key_value_delim": False,
4939        "duplicate_resolution_callback": False,
4940    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4943class NumberToStr(Func):
4944    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4947class FromBase(Func):
4948    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4951class Struct(Func):
4952    arg_types = {"expressions": True}
4953    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4956class StructExtract(Func):
4957    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4962class Stuff(Func):
4963    _sql_names = ["STUFF", "INSERT"]
4964    arg_types = {"this": True, "start": True, "length": True, "expression": True}
arg_types = {'this': True, 'start': True, 'length': True, 'expression': True}
key = 'stuff'
class Sum(AggFunc):
4967class Sum(AggFunc):
4968    pass
key = 'sum'
class Sqrt(Func):
4971class Sqrt(Func):
4972    pass
key = 'sqrt'
class Stddev(AggFunc):
4975class Stddev(AggFunc):
4976    pass
key = 'stddev'
class StddevPop(AggFunc):
4979class StddevPop(AggFunc):
4980    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4983class StddevSamp(AggFunc):
4984    pass
key = 'stddevsamp'
class TimeToStr(Func):
4987class TimeToStr(Func):
4988    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4991class TimeToTimeStr(Func):
4992    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4995class TimeToUnix(Func):
4996    pass
key = 'timetounix'
class TimeStrToDate(Func):
4999class TimeStrToDate(Func):
5000    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
5003class TimeStrToTime(Func):
5004    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
5007class TimeStrToUnix(Func):
5008    pass
key = 'timestrtounix'
class Trim(Func):
5011class Trim(Func):
5012    arg_types = {
5013        "this": True,
5014        "expression": False,
5015        "position": False,
5016        "collation": False,
5017    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
5020class TsOrDsAdd(Func, TimeUnit):
5021    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
5024class TsOrDsToDateStr(Func):
5025    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
5028class TsOrDsToDate(Func):
5029    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
5032class TsOrDiToDi(Func):
5033    pass
key = 'tsorditodi'
class Unhex(Func):
5036class Unhex(Func):
5037    pass
key = 'unhex'
class UnixToStr(Func):
5040class UnixToStr(Func):
5041    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
5046class UnixToTime(Func):
5047    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
5048
5049    SECONDS = Literal.string("seconds")
5050    MILLIS = Literal.string("millis")
5051    MICROS = Literal.string("micros")
arg_types = {'this': True, 'scale': False, 'zone': False, 'hours': False, 'minutes': False}
SECONDS = (LITERAL this: seconds, is_string: True)
MILLIS = (LITERAL this: millis, is_string: True)
MICROS = (LITERAL this: micros, is_string: True)
key = 'unixtotime'
class UnixToTimeStr(Func):
5054class UnixToTimeStr(Func):
5055    pass
key = 'unixtotimestr'
class Upper(Func):
5058class Upper(Func):
5059    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
5062class Variance(AggFunc):
5063    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
5066class VariancePop(AggFunc):
5067    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
5070class Week(Func):
5071    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
5074class XMLTable(Func):
5075    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
arg_types = {'this': True, 'passing': False, 'columns': False, 'by_ref': False}
key = 'xmltable'
class Year(Func):
5078class Year(Func):
5079    pass
key = 'year'
class Use(Expression):
5082class Use(Expression):
5083    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
5086class Merge(Expression):
5087    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
arg_types = {'this': True, 'using': True, 'on': True, 'expressions': True}
key = 'merge'
class When(Func):
5090class When(Func):
5091    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
arg_types = {'matched': True, 'source': False, 'condition': False, 'then': True}
key = 'when'
class NextValueFor(Func):
5096class NextValueFor(Func):
5097    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'Abs'>, <class 'AnyValue'>, <class 'ApproxDistinct'>, <class 'ApproxQuantile'>, <class 'Array'>, <class 'ArrayAgg'>, <class 'ArrayAll'>, <class 'ArrayAny'>, <class 'ArrayConcat'>, <class 'ArrayContains'>, <class 'ArrayFilter'>, <class 'ArrayJoin'>, <class 'ArraySize'>, <class 'ArraySort'>, <class 'ArraySum'>, <class 'ArrayUnionAgg'>, <class 'Avg'>, <class 'Case'>, <class 'Cast'>, <class 'CastToStrType'>, <class 'Ceil'>, <class 'Chr'>, <class 'Coalesce'>, <class 'Collate'>, <class 'Concat'>, <class 'ConcatWs'>, <class 'Count'>, <class 'CountIf'>, <class 'CurrentDate'>, <class 'CurrentDatetime'>, <class 'CurrentTime'>, <class 'CurrentTimestamp'>, <class 'CurrentUser'>, <class 'Date'>, <class 'DateAdd'>, <class 'DateDiff'>, <class 'DateFromParts'>, <class 'DateStrToDate'>, <class 'DateSub'>, <class 'DateToDateStr'>, <class 'DateToDi'>, <class 'DateTrunc'>, <class 'DatetimeAdd'>, <class 'DatetimeDiff'>, <class 'DatetimeSub'>, <class 'DatetimeTrunc'>, <class 'Day'>, <class 'DayOfMonth'>, <class 'DayOfWeek'>, <class 'DayOfYear'>, <class 'Decode'>, <class 'DiToDate'>, <class 'Encode'>, <class 'Exp'>, <class 'Explode'>, <class 'Extract'>, <class 'First'>, <class 'Floor'>, <class 'FromBase'>, <class 'FromBase64'>, <class 'GenerateSeries'>, <class 'Greatest'>, <class 'GroupConcat'>, <class 'Hex'>, <class 'Hll'>, <class 'If'>, <class 'Initcap'>, <class 'IsNan'>, <class 'JSONArray'>, <class 'JSONArrayAgg'>, <class 'JSONArrayContains'>, <class 'JSONBExtract'>, <class 'JSONBExtractScalar'>, <class 'JSONExtract'>, <class 'JSONExtractScalar'>, <class 'JSONFormat'>, <class 'JSONObject'>, <class 'JSONTable'>, <class 'Last'>, <class 'LastDateOfMonth'>, <class 'Least'>, <class 'Left'>, <class 'Length'>, <class 'Levenshtein'>, <class 'Ln'>, <class 'Log'>, <class 'Log10'>, <class 'Log2'>, <class 'LogicalAnd'>, <class 'LogicalOr'>, <class 'Lower'>, <class 'MD5'>, <class 'MD5Digest'>, <class 'Map'>, <class 'MapFromEntries'>, <class 'MatchAgainst'>, <class 'Max'>, <class 'Min'>, <class 'Month'>, <class 'MonthsBetween'>, <class 'NextValueFor'>, <class 'NumberToStr'>, <class 'Nvl2'>, <class 'OpenJSON'>, <class 'ParameterizedAgg'>, <class 'ParseJSON'>, <class 'PercentileCont'>, <class 'PercentileDisc'>, <class 'Posexplode'>, <class 'Pow'>, <class 'Predict'>, <class 'Quantile'>, <class 'RangeN'>, <class 'ReadCSV'>, <class 'Reduce'>, <class 'RegexpExtract'>, <class 'RegexpILike'>, <class 'RegexpLike'>, <class 'RegexpReplace'>, <class 'RegexpSplit'>, <class 'Repeat'>, <class 'Right'>, <class 'Round'>, <class 'RowNumber'>, <class 'SHA'>, <class 'SHA2'>, <class 'SafeConcat'>, <class 'SafeDivide'>, <class 'SetAgg'>, <class 'SortArray'>, <class 'Split'>, <class 'Sqrt'>, <class 'StandardHash'>, <class 'StarMap'>, <class 'StartsWith'>, <class 'Stddev'>, <class 'StddevPop'>, <class 'StddevSamp'>, <class 'StrPosition'>, <class 'StrToDate'>, <class 'StrToMap'>, <class 'StrToTime'>, <class 'StrToUnix'>, <class 'Struct'>, <class 'StructExtract'>, <class 'Stuff'>, <class 'Substring'>, <class 'Sum'>, <class 'TimeAdd'>, <class 'TimeDiff'>, <class 'TimeStrToDate'>, <class 'TimeStrToTime'>, <class 'TimeStrToUnix'>, <class 'TimeSub'>, <class 'TimeToStr'>, <class 'TimeToTimeStr'>, <class 'TimeToUnix'>, <class 'TimeTrunc'>, <class 'Timestamp'>, <class 'TimestampAdd'>, <class 'TimestampDiff'>, <class 'TimestampSub'>, <class 'TimestampTrunc'>, <class 'ToBase64'>, <class 'ToChar'>, <class 'ToDays'>, <class 'Transform'>, <class 'Trim'>, <class 'TryCast'>, <class 'TsOrDiToDi'>, <class 'TsOrDsAdd'>, <class 'TsOrDsToDate'>, <class 'TsOrDsToDateStr'>, <class 'Unhex'>, <class 'UnixToStr'>, <class 'UnixToTime'>, <class 'UnixToTimeStr'>, <class 'Upper'>, <class 'VarMap'>, <class 'Variance'>, <class 'VariancePop'>, <class 'Week'>, <class 'WeekOfYear'>, <class 'When'>, <class 'XMLTable'>, <class 'Xor'>, <class 'Year'>]
def maybe_parse( sql_or_expression: Union[str, Expression], *, into: Union[str, Type[Expression], Collection[Union[str, Type[Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> Expression:
5134def maybe_parse(
5135    sql_or_expression: ExpOrStr,
5136    *,
5137    into: t.Optional[IntoType] = None,
5138    dialect: DialectType = None,
5139    prefix: t.Optional[str] = None,
5140    copy: bool = False,
5141    **opts,
5142) -> Expression:
5143    """Gracefully handle a possible string or expression.
5144
5145    Example:
5146        >>> maybe_parse("1")
5147        (LITERAL this: 1, is_string: False)
5148        >>> maybe_parse(to_identifier("x"))
5149        (IDENTIFIER this: x, quoted: False)
5150
5151    Args:
5152        sql_or_expression: the SQL code string or an expression
5153        into: the SQLGlot Expression to parse into
5154        dialect: the dialect used to parse the input expressions (in the case that an
5155            input expression is a SQL string).
5156        prefix: a string to prefix the sql with before it gets parsed
5157            (automatically includes a space)
5158        copy: whether or not to copy the expression.
5159        **opts: other options to use to parse the input expressions (again, in the case
5160            that an input expression is a SQL string).
5161
5162    Returns:
5163        Expression: the parsed or given expression.
5164    """
5165    if isinstance(sql_or_expression, Expression):
5166        if copy:
5167            return sql_or_expression.copy()
5168        return sql_or_expression
5169
5170    if sql_or_expression is None:
5171        raise ParseError(f"SQL cannot be None")
5172
5173    import sqlglot
5174
5175    sql = str(sql_or_expression)
5176    if prefix:
5177        sql = f"{prefix} {sql}"
5178
5179    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def maybe_copy(instance, copy=True):
5192def maybe_copy(instance, copy=True):
5193    return instance.copy() if copy and instance else instance
def union( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Union:
5374def union(
5375    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5376) -> Union:
5377    """
5378    Initializes a syntax tree from one UNION expression.
5379
5380    Example:
5381        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5382        'SELECT * FROM foo UNION SELECT * FROM bla'
5383
5384    Args:
5385        left: the SQL code string corresponding to the left-hand side.
5386            If an `Expression` instance is passed, it will be used as-is.
5387        right: the SQL code string corresponding to the right-hand side.
5388            If an `Expression` instance is passed, it will be used as-is.
5389        distinct: set the DISTINCT flag if and only if this is true.
5390        dialect: the dialect used to parse the input expression.
5391        opts: other options to use to parse the input expressions.
5392
5393    Returns:
5394        The new Union instance.
5395    """
5396    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5397    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5398
5399    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union instance.

def intersect( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Intersect:
5402def intersect(
5403    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5404) -> Intersect:
5405    """
5406    Initializes a syntax tree from one INTERSECT expression.
5407
5408    Example:
5409        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5410        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5411
5412    Args:
5413        left: the SQL code string corresponding to the left-hand side.
5414            If an `Expression` instance is passed, it will be used as-is.
5415        right: the SQL code string corresponding to the right-hand side.
5416            If an `Expression` instance is passed, it will be used as-is.
5417        distinct: set the DISTINCT flag if and only if this is true.
5418        dialect: the dialect used to parse the input expression.
5419        opts: other options to use to parse the input expressions.
5420
5421    Returns:
5422        The new Intersect instance.
5423    """
5424    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5425    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5426
5427    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect instance.

def except_( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Except:
5430def except_(
5431    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5432) -> Except:
5433    """
5434    Initializes a syntax tree from one EXCEPT expression.
5435
5436    Example:
5437        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5438        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5439
5440    Args:
5441        left: the SQL code string corresponding to the left-hand side.
5442            If an `Expression` instance is passed, it will be used as-is.
5443        right: the SQL code string corresponding to the right-hand side.
5444            If an `Expression` instance is passed, it will be used as-is.
5445        distinct: set the DISTINCT flag if and only if this is true.
5446        dialect: the dialect used to parse the input expression.
5447        opts: other options to use to parse the input expressions.
5448
5449    Returns:
5450        The new Except instance.
5451    """
5452    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5453    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5454
5455    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except instance.

def select( *expressions: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5458def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5459    """
5460    Initializes a syntax tree from one or multiple SELECT expressions.
5461
5462    Example:
5463        >>> select("col1", "col2").from_("tbl").sql()
5464        'SELECT col1, col2 FROM tbl'
5465
5466    Args:
5467        *expressions: the SQL code string to parse as the expressions of a
5468            SELECT statement. If an Expression instance is passed, this is used as-is.
5469        dialect: the dialect used to parse the input expressions (in the case that an
5470            input expression is a SQL string).
5471        **opts: other options to use to parse the input expressions (again, in the case
5472            that an input expression is a SQL string).
5473
5474    Returns:
5475        Select: the syntax tree for the SELECT statement.
5476    """
5477    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_( expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5480def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5481    """
5482    Initializes a syntax tree from a FROM expression.
5483
5484    Example:
5485        >>> from_("tbl").select("col1", "col2").sql()
5486        'SELECT col1, col2 FROM tbl'
5487
5488    Args:
5489        *expression: the SQL code string to parse as the FROM expressions of a
5490            SELECT statement. If an Expression instance is passed, this is used as-is.
5491        dialect: the dialect used to parse the input expression (in the case that the
5492            input expression is a SQL string).
5493        **opts: other options to use to parse the input expressions (again, in the case
5494            that the input expression is a SQL string).
5495
5496    Returns:
5497        Select: the syntax tree for the SELECT statement.
5498    """
5499    return Select().from_(expression, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | Table, properties: dict, where: Union[str, Expression, NoneType] = None, from_: Union[str, Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Update:
5502def update(
5503    table: str | Table,
5504    properties: dict,
5505    where: t.Optional[ExpOrStr] = None,
5506    from_: t.Optional[ExpOrStr] = None,
5507    dialect: DialectType = None,
5508    **opts,
5509) -> Update:
5510    """
5511    Creates an update statement.
5512
5513    Example:
5514        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5515        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5516
5517    Args:
5518        *properties: dictionary of properties to set which are
5519            auto converted to sql objects eg None -> NULL
5520        where: sql conditional parsed into a WHERE statement
5521        from_: sql statement parsed into a FROM statement
5522        dialect: the dialect used to parse the input expressions.
5523        **opts: other options to use to parse the input expressions.
5524
5525    Returns:
5526        Update: the syntax tree for the UPDATE statement.
5527    """
5528    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5529    update_expr.set(
5530        "expressions",
5531        [
5532            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5533            for k, v in properties.items()
5534        ],
5535    )
5536    if from_:
5537        update_expr.set(
5538            "from",
5539            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5540        )
5541    if isinstance(where, Condition):
5542        where = Where(this=where)
5543    if where:
5544        update_expr.set(
5545            "where",
5546            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5547        )
5548    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, Expression], where: Union[str, Expression, NoneType] = None, returning: Union[str, Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Delete:
5551def delete(
5552    table: ExpOrStr,
5553    where: t.Optional[ExpOrStr] = None,
5554    returning: t.Optional[ExpOrStr] = None,
5555    dialect: DialectType = None,
5556    **opts,
5557) -> Delete:
5558    """
5559    Builds a delete statement.
5560
5561    Example:
5562        >>> delete("my_table", where="id > 1").sql()
5563        'DELETE FROM my_table WHERE id > 1'
5564
5565    Args:
5566        where: sql conditional parsed into a WHERE statement
5567        returning: sql conditional parsed into a RETURNING statement
5568        dialect: the dialect used to parse the input expressions.
5569        **opts: other options to use to parse the input expressions.
5570
5571    Returns:
5572        Delete: the syntax tree for the DELETE statement.
5573    """
5574    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5575    if where:
5576        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5577    if returning:
5578        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5579    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def insert( expression: Union[str, Expression], into: Union[str, Expression], columns: Optional[Sequence[Union[str, Expression]]] = None, overwrite: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Insert:
5582def insert(
5583    expression: ExpOrStr,
5584    into: ExpOrStr,
5585    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5586    overwrite: t.Optional[bool] = None,
5587    dialect: DialectType = None,
5588    copy: bool = True,
5589    **opts,
5590) -> Insert:
5591    """
5592    Builds an INSERT statement.
5593
5594    Example:
5595        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5596        'INSERT INTO tbl VALUES (1, 2, 3)'
5597
5598    Args:
5599        expression: the sql string or expression of the INSERT statement
5600        into: the tbl to insert data to.
5601        columns: optionally the table's column names.
5602        overwrite: whether to INSERT OVERWRITE or not.
5603        dialect: the dialect used to parse the input expressions.
5604        copy: whether or not to copy the expression.
5605        **opts: other options to use to parse the input expressions.
5606
5607    Returns:
5608        Insert: the syntax tree for the INSERT statement.
5609    """
5610    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5611    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5612
5613    if columns:
5614        this = _apply_list_builder(
5615            *columns,
5616            instance=Schema(this=this),
5617            arg="expressions",
5618            into=Identifier,
5619            copy=False,
5620            dialect=dialect,
5621            **opts,
5622        )
5623
5624    return Insert(this=this, expression=expr, overwrite=overwrite)

Builds an INSERT statement.

Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql()
'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
  • expression: the sql string or expression of the INSERT statement
  • into: the tbl to insert data to.
  • columns: optionally the table's column names.
  • overwrite: whether to INSERT OVERWRITE or not.
  • dialect: the dialect used to parse the input expressions.
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Insert: the syntax tree for the INSERT statement.

def condition( expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
5627def condition(
5628    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5629) -> Condition:
5630    """
5631    Initialize a logical condition expression.
5632
5633    Example:
5634        >>> condition("x=1").sql()
5635        'x = 1'
5636
5637        This is helpful for composing larger logical syntax trees:
5638        >>> where = condition("x=1")
5639        >>> where = where.and_("y=1")
5640        >>> Select().from_("tbl").select("*").where(where).sql()
5641        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5642
5643    Args:
5644        *expression: the SQL code string to parse.
5645            If an Expression instance is passed, this is used as-is.
5646        dialect: the dialect used to parse the input expression (in the case that the
5647            input expression is a SQL string).
5648        copy: Whether or not to copy `expression` (only applies to expressions).
5649        **opts: other options to use to parse the input expressions (again, in the case
5650            that the input expression is a SQL string).
5651
5652    Returns:
5653        The new Condition instance
5654    """
5655    return maybe_parse(
5656        expression,
5657        into=Condition,
5658        dialect=dialect,
5659        copy=copy,
5660        **opts,
5661    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy: Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

The new Condition instance

def and_( *expressions: Union[str, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
5664def and_(
5665    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5666) -> Condition:
5667    """
5668    Combine multiple conditions with an AND logical operator.
5669
5670    Example:
5671        >>> and_("x=1", and_("y=1", "z=1")).sql()
5672        'x = 1 AND (y = 1 AND z = 1)'
5673
5674    Args:
5675        *expressions: the SQL code strings to parse.
5676            If an Expression instance is passed, this is used as-is.
5677        dialect: the dialect used to parse the input expression.
5678        copy: whether or not to copy `expressions` (only applies to Expressions).
5679        **opts: other options to use to parse the input expressions.
5680
5681    Returns:
5682        And: the new condition
5683    """
5684    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_( *expressions: Union[str, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
5687def or_(
5688    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5689) -> Condition:
5690    """
5691    Combine multiple conditions with an OR logical operator.
5692
5693    Example:
5694        >>> or_("x=1", or_("y=1", "z=1")).sql()
5695        'x = 1 OR (y = 1 OR z = 1)'
5696
5697    Args:
5698        *expressions: the SQL code strings to parse.
5699            If an Expression instance is passed, this is used as-is.
5700        dialect: the dialect used to parse the input expression.
5701        copy: whether or not to copy `expressions` (only applies to Expressions).
5702        **opts: other options to use to parse the input expressions.
5703
5704    Returns:
5705        Or: the new condition
5706    """
5707    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_( expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Not:
5710def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5711    """
5712    Wrap a condition with a NOT operator.
5713
5714    Example:
5715        >>> not_("this_suit='black'").sql()
5716        "NOT this_suit = 'black'"
5717
5718    Args:
5719        expression: the SQL code string to parse.
5720            If an Expression instance is passed, this is used as-is.
5721        dialect: the dialect used to parse the input expression.
5722        copy: whether to copy the expression or not.
5723        **opts: other options to use to parse the input expressions.
5724
5725    Returns:
5726        The new condition.
5727    """
5728    this = condition(
5729        expression,
5730        dialect=dialect,
5731        copy=copy,
5732        **opts,
5733    )
5734    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression or not.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition.

def paren( expression: Union[str, Expression], copy: bool = True) -> Paren:
5737def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5738    """
5739    Wrap an expression in parentheses.
5740
5741    Example:
5742        >>> paren("5 + 3").sql()
5743        '(5 + 3)'
5744
5745    Args:
5746        expression: the SQL code string to parse.
5747            If an Expression instance is passed, this is used as-is.
5748        copy: whether to copy the expression or not.
5749
5750    Returns:
5751        The wrapped expression.
5752    """
5753    return Paren(this=maybe_parse(expression, copy=copy))

Wrap an expression in parentheses.

Example:
>>> paren("5 + 3").sql()
'(5 + 3)'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • copy: whether to copy the expression or not.
Returns:

The wrapped expression.

SAFE_IDENTIFIER_RE = re.compile('^[_a-zA-Z][\\w]*$')
def to_identifier(name, quoted=None, copy=True):
5771def to_identifier(name, quoted=None, copy=True):
5772    """Builds an identifier.
5773
5774    Args:
5775        name: The name to turn into an identifier.
5776        quoted: Whether or not force quote the identifier.
5777        copy: Whether or not to copy a passed in Identefier node.
5778
5779    Returns:
5780        The identifier ast node.
5781    """
5782
5783    if name is None:
5784        return None
5785
5786    if isinstance(name, Identifier):
5787        identifier = maybe_copy(name, copy)
5788    elif isinstance(name, str):
5789        identifier = Identifier(
5790            this=name,
5791            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5792        )
5793    else:
5794        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5795    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
  • copy: Whether or not to copy a passed in Identefier node.
Returns:

The identifier ast node.

INTERVAL_STRING_RE = re.compile('\\s*([0-9]+)\\s*([a-zA-Z]+)\\s*')
def to_interval( interval: str | Literal) -> Interval:
5801def to_interval(interval: str | Literal) -> Interval:
5802    """Builds an interval expression from a string like '1 day' or '5 months'."""
5803    if isinstance(interval, Literal):
5804        if not interval.is_string:
5805            raise ValueError("Invalid interval string.")
5806
5807        interval = interval.this
5808
5809    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5810
5811    if not interval_parts:
5812        raise ValueError("Invalid interval string.")
5813
5814    return Interval(
5815        this=Literal.string(interval_parts.group(1)),
5816        unit=Var(this=interval_parts.group(2)),
5817    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[Table]:
5830def to_table(
5831    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5832) -> t.Optional[Table]:
5833    """
5834    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5835    If a table is passed in then that table is returned.
5836
5837    Args:
5838        sql_path: a `[catalog].[schema].[table]` string.
5839        dialect: the source dialect according to which the table name will be parsed.
5840        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5841
5842    Returns:
5843        A table expression.
5844    """
5845    if sql_path is None or isinstance(sql_path, Table):
5846        return sql_path
5847    if not isinstance(sql_path, str):
5848        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5849
5850    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5851    if table:
5852        for k, v in kwargs.items():
5853            table.set(k, v)
5854
5855    return table

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
  • dialect: the source dialect according to which the table name will be parsed.
  • kwargs: the kwargs to instantiate the resulting Table expression with.
Returns:

A table expression.

def to_column( sql_path: str | Column, **kwargs) -> Column:
5858def to_column(sql_path: str | Column, **kwargs) -> Column:
5859    """
5860    Create a column from a `[table].[column]` sql path. Schema is optional.
5861
5862    If a column is passed in then that column is returned.
5863
5864    Args:
5865        sql_path: `[table].[column]` string
5866    Returns:
5867        Table: A column expression
5868    """
5869    if sql_path is None or isinstance(sql_path, Column):
5870        return sql_path
5871    if not isinstance(sql_path, str):
5872        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5873    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, Expression], alias: str | Identifier, table: Union[bool, Sequence[str | Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
5876def alias_(
5877    expression: ExpOrStr,
5878    alias: str | Identifier,
5879    table: bool | t.Sequence[str | Identifier] = False,
5880    quoted: t.Optional[bool] = None,
5881    dialect: DialectType = None,
5882    copy: bool = True,
5883    **opts,
5884):
5885    """Create an Alias expression.
5886
5887    Example:
5888        >>> alias_('foo', 'bar').sql()
5889        'foo AS bar'
5890
5891        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5892        '(SELECT 1, 2) AS bar(a, b)'
5893
5894    Args:
5895        expression: the SQL code strings to parse.
5896            If an Expression instance is passed, this is used as-is.
5897        alias: the alias name to use. If the name has
5898            special characters it is quoted.
5899        table: Whether or not to create a table alias, can also be a list of columns.
5900        quoted: whether or not to quote the alias
5901        dialect: the dialect used to parse the input expression.
5902        copy: Whether or not to copy the expression.
5903        **opts: other options to use to parse the input expressions.
5904
5905    Returns:
5906        Alias: the aliased expression
5907    """
5908    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5909    alias = to_identifier(alias, quoted=quoted)
5910
5911    if table:
5912        table_alias = TableAlias(this=alias)
5913        exp.set("alias", table_alias)
5914
5915        if not isinstance(table, bool):
5916            for column in table:
5917                table_alias.append("columns", to_identifier(column, quoted=quoted))
5918
5919        return exp
5920
5921    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5922    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5923    # for the complete Window expression.
5924    #
5925    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5926
5927    if "alias" in exp.arg_types and not isinstance(exp, Window):
5928        exp.set("alias", alias)
5929        return exp
5930    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery( expression: Union[str, Expression], alias: Union[Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5933def subquery(
5934    expression: ExpOrStr,
5935    alias: t.Optional[Identifier | str] = None,
5936    dialect: DialectType = None,
5937    **opts,
5938) -> Select:
5939    """
5940    Build a subquery expression.
5941
5942    Example:
5943        >>> subquery('select x from tbl', 'bar').select('x').sql()
5944        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5945
5946    Args:
5947        expression: the SQL code strings to parse.
5948            If an Expression instance is passed, this is used as-is.
5949        alias: the alias name to use.
5950        dialect: the dialect used to parse the input expression.
5951        **opts: other options to use to parse the input expressions.
5952
5953    Returns:
5954        A new Select instance with the subquery expression included.
5955    """
5956
5957    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5958    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use.
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

A new Select instance with the subquery expression included.

def column( col: str | Identifier, table: Union[Identifier, str, NoneType] = None, db: Union[Identifier, str, NoneType] = None, catalog: Union[Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> Column:
5961def column(
5962    col: str | Identifier,
5963    table: t.Optional[str | Identifier] = None,
5964    db: t.Optional[str | Identifier] = None,
5965    catalog: t.Optional[str | Identifier] = None,
5966    quoted: t.Optional[bool] = None,
5967) -> Column:
5968    """
5969    Build a Column.
5970
5971    Args:
5972        col: Column name.
5973        table: Table name.
5974        db: Database name.
5975        catalog: Catalog name.
5976        quoted: Whether to force quotes on the column's identifiers.
5977
5978    Returns:
5979        The new Column instance.
5980    """
5981    return Column(
5982        this=to_identifier(col, quoted=quoted),
5983        table=to_identifier(table, quoted=quoted),
5984        db=to_identifier(db, quoted=quoted),
5985        catalog=to_identifier(catalog, quoted=quoted),
5986    )

Build a Column.

Arguments:
  • col: Column name.
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quoted: Whether to force quotes on the column's identifiers.
Returns:

The new Column instance.

def cast( expression: Union[str, Expression], to: str | DataType | DataType.Type, **opts) -> Cast:
5989def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5990    """Cast an expression to a data type.
5991
5992    Example:
5993        >>> cast('x + 1', 'int').sql()
5994        'CAST(x + 1 AS INT)'
5995
5996    Args:
5997        expression: The expression to cast.
5998        to: The datatype to cast to.
5999
6000    Returns:
6001        The new Cast instance.
6002    """
6003    expression = maybe_parse(expression, **opts)
6004    data_type = DataType.build(to, **opts)
6005    expression = Cast(this=expression, to=data_type)
6006    expression.type = data_type
6007    return expression

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

The new Cast instance.

def table_( table: Identifier | str, db: Union[Identifier, str, NoneType] = None, catalog: Union[Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[Identifier, str, NoneType] = None) -> Table:
6010def table_(
6011    table: Identifier | str,
6012    db: t.Optional[Identifier | str] = None,
6013    catalog: t.Optional[Identifier | str] = None,
6014    quoted: t.Optional[bool] = None,
6015    alias: t.Optional[Identifier | str] = None,
6016) -> Table:
6017    """Build a Table.
6018
6019    Args:
6020        table: Table name.
6021        db: Database name.
6022        catalog: Catalog name.
6023        quote: Whether to force quotes on the table's identifiers.
6024        alias: Table's alias.
6025
6026    Returns:
6027        The new Table instance.
6028    """
6029    return Table(
6030        this=to_identifier(table, quoted=quoted) if table else None,
6031        db=to_identifier(db, quoted=quoted) if db else None,
6032        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
6033        alias=TableAlias(this=to_identifier(alias)) if alias else None,
6034    )

Build a Table.

Arguments:
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quote: Whether to force quotes on the table's identifiers.
  • alias: Table's alias.
Returns:

The new Table instance.

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, DataType], NoneType] = None) -> Values:
6037def values(
6038    values: t.Iterable[t.Tuple[t.Any, ...]],
6039    alias: t.Optional[str] = None,
6040    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
6041) -> Values:
6042    """Build VALUES statement.
6043
6044    Example:
6045        >>> values([(1, '2')]).sql()
6046        "VALUES (1, '2')"
6047
6048    Args:
6049        values: values statements that will be converted to SQL
6050        alias: optional alias
6051        columns: Optional list of ordered column names or ordered dictionary of column names to types.
6052         If either are provided then an alias is also required.
6053
6054    Returns:
6055        Values: the Values expression object
6056    """
6057    if columns and not alias:
6058        raise ValueError("Alias is required when providing columns")
6059
6060    return Values(
6061        expressions=[convert(tup) for tup in values],
6062        alias=(
6063            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
6064            if columns
6065            else (TableAlias(this=to_identifier(alias)) if alias else None)
6066        ),
6067    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, Expression, NoneType]) -> Var:
6070def var(name: t.Optional[ExpOrStr]) -> Var:
6071    """Build a SQL variable.
6072
6073    Example:
6074        >>> repr(var('x'))
6075        '(VAR this: x)'
6076
6077        >>> repr(var(column('x', table='y')))
6078        '(VAR this: x)'
6079
6080    Args:
6081        name: The name of the var or an expression who's name will become the var.
6082
6083    Returns:
6084        The new variable node.
6085    """
6086    if not name:
6087        raise ValueError("Cannot convert empty name into var.")
6088
6089    if isinstance(name, Expression):
6090        name = name.name
6091    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | Table, new_name: str | Table) -> AlterTable:
6094def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
6095    """Build ALTER TABLE... RENAME... expression
6096
6097    Args:
6098        old_name: The old name of the table
6099        new_name: The new name of the table
6100
6101    Returns:
6102        Alter table expression
6103    """
6104    old_table = to_table(old_name)
6105    new_table = to_table(new_name)
6106    return AlterTable(
6107        this=old_table,
6108        actions=[
6109            RenameTable(this=new_table),
6110        ],
6111    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> Expression:
6114def convert(value: t.Any, copy: bool = False) -> Expression:
6115    """Convert a python value into an expression object.
6116
6117    Raises an error if a conversion is not possible.
6118
6119    Args:
6120        value: A python object.
6121        copy: Whether or not to copy `value` (only applies to Expressions and collections).
6122
6123    Returns:
6124        Expression: the equivalent expression object.
6125    """
6126    if isinstance(value, Expression):
6127        return maybe_copy(value, copy)
6128    if isinstance(value, str):
6129        return Literal.string(value)
6130    if isinstance(value, bool):
6131        return Boolean(this=value)
6132    if value is None or (isinstance(value, float) and math.isnan(value)):
6133        return NULL
6134    if isinstance(value, numbers.Number):
6135        return Literal.number(value)
6136    if isinstance(value, datetime.datetime):
6137        datetime_literal = Literal.string(
6138            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
6139        )
6140        return TimeStrToTime(this=datetime_literal)
6141    if isinstance(value, datetime.date):
6142        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6143        return DateStrToDate(this=date_literal)
6144    if isinstance(value, tuple):
6145        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6146    if isinstance(value, list):
6147        return Array(expressions=[convert(v, copy=copy) for v in value])
6148    if isinstance(value, dict):
6149        return Map(
6150            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6151            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6152        )
6153    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children( expression: Expression, fun: Callable, *args, **kwargs) -> None:
6156def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6157    """
6158    Replace children of an expression with the result of a lambda fun(child) -> exp.
6159    """
6160    for k, v in expression.args.items():
6161        is_list_arg = type(v) is list
6162
6163        child_nodes = v if is_list_arg else [v]
6164        new_child_nodes = []
6165
6166        for cn in child_nodes:
6167            if isinstance(cn, Expression):
6168                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6169                    new_child_nodes.append(child_node)
6170                    child_node.parent = expression
6171                    child_node.arg_key = k
6172            else:
6173                new_child_nodes.append(cn)
6174
6175        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names( expression: Expression, exclude: str = '') -> Set[str]:
6178def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6179    """
6180    Return all table names referenced through columns in an expression.
6181
6182    Example:
6183        >>> import sqlglot
6184        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6185        ['a', 'c']
6186
6187    Args:
6188        expression: expression to find table names.
6189        exclude: a table name to exclude
6190
6191    Returns:
6192        A list of unique names.
6193    """
6194    return {
6195        table
6196        for table in (column.table for column in expression.find_all(Column))
6197        if table and table != exclude
6198    }

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
['a', 'c']
Arguments:
  • expression: expression to find table names.
  • exclude: a table name to exclude
Returns:

A list of unique names.

def table_name( table: Table | str, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) -> str:
6201def table_name(table: Table | str, dialect: DialectType = None) -> str:
6202    """Get the full name of a table as a string.
6203
6204    Args:
6205        table: Table expression node or string.
6206        dialect: The dialect to generate the table name for.
6207
6208    Examples:
6209        >>> from sqlglot import exp, parse_one
6210        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6211        'a.b.c'
6212
6213    Returns:
6214        The table name.
6215    """
6216
6217    table = maybe_parse(table, into=Table, dialect=dialect)
6218
6219    if not table:
6220        raise ValueError(f"Cannot parse {table}")
6221
6222    return ".".join(
6223        part.sql(dialect=dialect, identify=True)
6224        if not SAFE_IDENTIFIER_RE.match(part.name)
6225        else part.name
6226        for part in table.parts
6227    )

Get the full name of a table as a string.

Arguments:
  • table: Table expression node or string.
  • dialect: The dialect to generate the table name for.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression: ~E, mapping: Dict[str, str], copy: bool = True) -> ~E:
6230def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6231    """Replace all tables in expression according to the mapping.
6232
6233    Args:
6234        expression: expression node to be transformed and replaced.
6235        mapping: mapping of table names.
6236        copy: whether or not to copy the expression.
6237
6238    Examples:
6239        >>> from sqlglot import exp, parse_one
6240        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6241        'SELECT * FROM c'
6242
6243    Returns:
6244        The mapped expression.
6245    """
6246
6247    def _replace_tables(node: Expression) -> Expression:
6248        if isinstance(node, Table):
6249            new_name = mapping.get(table_name(node))
6250            if new_name:
6251                return to_table(
6252                    new_name,
6253                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6254                )
6255        return node
6256
6257    return expression.transform(_replace_tables, copy=copy)

Replace all tables in expression according to the mapping.

Arguments:
  • expression: expression node to be transformed and replaced.
  • mapping: mapping of table names.
  • copy: whether or not to copy the expression.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders( expression: Expression, *args, **kwargs) -> Expression:
6260def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6261    """Replace placeholders in an expression.
6262
6263    Args:
6264        expression: expression node to be transformed and replaced.
6265        args: positional names that will substitute unnamed placeholders in the given order.
6266        kwargs: keyword arguments that will substitute named placeholders.
6267
6268    Examples:
6269        >>> from sqlglot import exp, parse_one
6270        >>> replace_placeholders(
6271        ...     parse_one("select * from :tbl where ? = ?"),
6272        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6273        ... ).sql()
6274        "SELECT * FROM foo WHERE str_col = 'b'"
6275
6276    Returns:
6277        The mapped expression.
6278    """
6279
6280    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6281        if isinstance(node, Placeholder):
6282            if node.name:
6283                new_name = kwargs.get(node.name)
6284                if new_name:
6285                    return convert(new_name)
6286            else:
6287                try:
6288                    return convert(next(args))
6289                except StopIteration:
6290                    pass
6291        return node
6292
6293    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression: expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: Expression, sources: Dict[str, Subqueryable], copy: bool = True) -> Expression:
6296def expand(
6297    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6298) -> Expression:
6299    """Transforms an expression by expanding all referenced sources into subqueries.
6300
6301    Examples:
6302        >>> from sqlglot import parse_one
6303        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6304        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6305
6306        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6307        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6308
6309    Args:
6310        expression: The expression to expand.
6311        sources: A dictionary of name to Subqueryables.
6312        copy: Whether or not to copy the expression during transformation. Defaults to True.
6313
6314    Returns:
6315        The transformed expression.
6316    """
6317
6318    def _expand(node: Expression):
6319        if isinstance(node, Table):
6320            name = table_name(node)
6321            source = sources.get(name)
6322            if source:
6323                subquery = source.subquery(node.alias or name)
6324                subquery.comments = [f"source: {name}"]
6325                return subquery.transform(_expand, copy=False)
6326        return node
6327
6328    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Func:
6331def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6332    """
6333    Returns a Func expression.
6334
6335    Examples:
6336        >>> func("abs", 5).sql()
6337        'ABS(5)'
6338
6339        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6340        'CAST(5 AS DOUBLE)'
6341
6342    Args:
6343        name: the name of the function to build.
6344        args: the args used to instantiate the function of interest.
6345        dialect: the source dialect.
6346        kwargs: the kwargs used to instantiate the function of interest.
6347
6348    Note:
6349        The arguments `args` and `kwargs` are mutually exclusive.
6350
6351    Returns:
6352        An instance of the function of interest, or an anonymous function, if `name` doesn't
6353        correspond to an existing `sqlglot.expressions.Func` class.
6354    """
6355    if args and kwargs:
6356        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6357
6358    from sqlglot.dialects.dialect import Dialect
6359
6360    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6361    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6362
6363    parser = Dialect.get_or_raise(dialect)().parser()
6364    from_args_list = parser.FUNCTIONS.get(name.upper())
6365
6366    if from_args_list:
6367        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6368    else:
6369        kwargs = kwargs or {"expressions": converted}
6370        function = Anonymous(this=name, **kwargs)
6371
6372    for error_message in function.error_messages(converted):
6373        raise ValueError(error_message)
6374
6375    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing Func class.

def true() -> Boolean:
6378def true() -> Boolean:
6379    """
6380    Returns a true Boolean expression.
6381    """
6382    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> Boolean:
6385def false() -> Boolean:
6386    """
6387    Returns a false Boolean expression.
6388    """
6389    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> Null:
6392def null() -> Null:
6393    """
6394    Returns a Null expression.
6395    """
6396    return Null()

Returns a Null expression.

TRUE = (BOOLEAN this: True)
FALSE = (BOOLEAN this: False)
NULL = (NULL )